我如何在MongoDB的引用字段上查询



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

用户

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

帖子

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

我想在帖子集合上创建一个查询,以返回以下内容:

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

有什么方法可以在Raw MongoDB中做到这一点?我正在使用mongoDB node.js客户端。

使用与查找操作员进行聚合。

db.posts.aggregate([
{"$lookup":{
    "from":"users",
    "localField":"author",
    "foreignField":"_id",
    "as":"author"
}},
{"$addFields":{
    "author": {"$arrayElemAt":["$author",0]}
}}])
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]
                    }
                },

            }
        },
    ]

);

最新更新