代码之家  ›  专栏  ›  技术社区  ›  CodyBugstein

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

  •  0
  • CodyBugstein  · 技术社区  · 7 年前

    我有两个系列, users posts . 典型文档的相关部分如下所示:

    使用者

    {
       "_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节点。js客户端。

    2 回复  |  直到 7 年前
        1
  •  1
  •   s7vr    7 年前

    将聚合与查找运算符一起使用。

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