仅从嵌套文档中返回查询元素及其父元素

时间:2014-08-02 19:21:18

标签: node.js mongodb mongoose

我有以下架构结构

Artist Schema
albums:[Albums Schema]

Album Schema
songs:[Songs Schema]

现在,我想通过歌曲ID搜索并返回歌曲,其父级专辑和艺术家详细信息。除了匹配之外,我不想再回复一首歌和专辑。到目前为止,我只能限制它使用位置或elemMatch返回查询的专辑,但它仍然返回所有歌曲。有没有人知道将歌曲和专辑元素限制为一种方式?

1 个答案:

答案 0 :(得分:2)

以下示例使用mongo shell以方便使用,但应该如此 直接翻译。

假设您的模式类似于:

db.artist.insert({
    name: '"Weird Al" Yankovic',
    albums: [
        {
            name: 'Dare to Be Stupid',
            year: 1995,
            songs: [
                { track: 'A1', name: 'Like a Surgeon' },
                { track: 'A2', name: 'Dare to Be Stupid' },
                { track: 'A3', name: 'I Want a New Duck' },
            ],
        },
        {
            name: 'Polka Party!',
            year: 1985,
            songs: [
                { track: 'A1', name: 'Living with a Hernia' },
                { track: 'A2', name: 'Dog Eat Dog' },
                { track: 'A3', name: 'Addicted to Spuds' },
            ],
        },
    ],
})

您可以使用Aggregation Framework获得预期结果:

db.artist.aggregate(

    // First match to reduce the number of candidate documents
    { $match: {
        "albums.songs.name": "I Want a New Duck",
    }},

    // Unwind 'albums' & 'songs' arrays
    { $unwind: "$albums" },
    { $unwind: "$albums.songs" },

    // Limit to matching song & album
    { $match: {
        "albums.songs.name": "I Want a New Duck",
    }}
)

示例结果:

{
    "_id" : ObjectId("53defb826ed136423e50d082"),
    "name" : "\"Weird Al\" Yankovic",
    "albums" : {
        "name" : "Dare to Be Stupid",
        "year" : 1995,
        "songs" : {
            "track" : "A3",
            "name" : "I Want a New Duck"
        }
    }
}