在Mongodb上使用查找

时间:2018-04-19 12:52:50

标签: mongodb lookup projection

我有三个系列:

案例

{
    "idStory": "story-5ac97232b2ea82701e853d0b",
    "chapters": [
        { "idChapter": "chapter-5ac97274b2ea82701e853d11" },
        { "idChapter": "chapter-5ac97593c9c35a7079f85f8c" }
    ]
}

章节

[
    {
        "idChapter": "chapter-5ac97274b2ea82701e853d11"
    },
    {
        "idChapter": "chapter-5ac97593c9c35a7079f85f8c",
        "images": [
            { "idImage": "image-5ac97593c9c35a7079f85f8c" },
            { "idImage": "image-5ac9f63f8bfb1b7b5bced68e" }
        ]
    }
]

图片

[
    {
        "idImage": "image-5ac97593c9c35a7079f85f8c",
        "URI": "http://mypath1"
        "dateCreation": "12/12/1973"
    },
    {
        "idImage": "image-5ac9f63f8bfb1b7b5bced68e",
        "URI": "http://mypath2"
        "dateCreation": "12/12/1973"
    }
]

我需要这个结果:

{
    "idStory": "story-5ac97232b2ea82701e853d0b",
    "chapters": [
        { "idChapter": "chapter-5ac97274b2ea82701e853d11" }
        {
            "idChapter": "chapter-5ac97593c9c35a7079f85f8c"
            "images": [
                { "URI": "http://mypath1" },
                { "URI": "http://mypath2" }
            ]
        }
    ]
}

我尝试过这个阶段:

  1. find 故事;
  2. $lookup用于相关的章节

    '$lookup': {
        'from': 'chapters',
        'localField': 'idChapter',
        'foreignField': 'idChapter',
        'as': 'chapters'
    }
    
  3. $unwind 章节

    '$unwind': '$chapters'
    
  4. $lookup用于相关的图片

    '$lookup': {
        'from': 'images',
        'localField': 'chapters.idImage',
        'foreignField': 'idImage',
        'as': 'images'
    }
    
  5. 最后$project

    '$project': {
        'idStory': true,
        'chapters': {
            'idChapter': '$chapters.idChapter',
            'images': {
                'URI': '$images.URI'
            }
        }
    }
    
  6. 但这不起作用:它总是重复unwinded数组上的第一个元素。

    任何帮助将不胜感激。

0 个答案:

没有答案