如何查询MongoDB中的引用字段?

时间:2018-02-06 23:08:29

标签: node.js mongodb reference mongodb-query dereference

我有两个集合,usersposts。典型文档的相关部分如下所示:

用户

{
   "_id": "user1",
   "name": "Joe",
   "age": 20
}

帖子

{
   "content": "Yo what's up!",
   "created": "2018-02-05T05:00:00.000Z",
   "author": "user1"
}

我想在posts集合上创建一个返回以下内容的查询:

{
       "content": "Yo what's up!",
       "created": "2018-02-05T05:00:00.000Z",
       "author": {
            "name": "Joe",
            "age": 20
}

有没有办法在原始MongoDB中执行此操作? 我正在使用MongoDB Node.js客户端。

2 个答案:

答案 0 :(得分:1)

使用聚合与查找运算符。

db.posts.aggregate([
{"$lookup":{
    "from":"users",
    "localField":"author",
    "foreignField":"_id",
    "as":"author"
}},
{"$addFields":{
    "author": {"$arrayElemAt":["$author",0]}
}}])

答案 1 :(得分:1)

db.posts.aggregate(

    // Pipeline
    [
        // Stage 1
        {
            $lookup: {
                "from": "user",
                "localField": "author",
                "foreignField": "_id",
                "as": "authorobj"
            }
        },

        // Stage 2
        {
            $project: {
                content: 1,
                created: 1,
                author: {
                    'name': {
                        "$arrayElemAt": ["$authorobj.name", 0]
                    },
                    'age': {
                        "$arrayElemAt": ["$authorobj.age", 0]
                    }
                },



            }
        },

    ]



);