【问题标题】:mongodb lookup in arraymongodb在数组中查找
【发布时间】:2021-07-02 14:16:57
【问题描述】:

当我在 mongodb 中进行查找时,我输入一个 as 字段并将数据加载到该字段中。但是,如果我有一个对象数组并且其中一个字段是 REF 字段,那么我总是会遇到这样的问题,即来自查找的数据总是加载到一个单独的字段中,而我无法在数组中找到它。如何进行查找,将数据直接加载到数组元素中。

例如

我有一个拥有一系列用户的组织,并且在该组织中的地位和角色

{
_id: "60cc87da3a530000173f6d33",
"baseData": {
    "name": "Organisation 1",
    "email": "org@gmail.com",
    "image": "",
    "description": "desc",
    "users": [
        {
           userID: "60cc87803a530000173f6d2d",
           userStatus: "active" ,
           userOrgRole: "Admin"
        },
        {
           userID: "60cc87803a530000173f9h4u",
           userStatus: "active" ,
           userOrgRole: "User"
        }
    ]
  }
}

当我进行查找并将 as 字段定义为 baseData.users 时,用户数组被用户数据覆盖。但是我如何将数据添加到每个用户数组中。

例如这是我需要的结果

{
_id: "60cc87da3a530000173f6d33",
"baseData": {
    "name": "Organisation 1",
    "email": "org@gmail.com",
    "image": "",
    "description": "desc",
    "users": [
        {
           userID: "60cc87803a530000173f6d2d",
           userStatus: "active" ,
           userOrgRole: "Admin"
           // userdata data from lookup for each array
        },
        {
           userID: "60cc87803a530000173f9h4u",
           userStatus: "active" ,
           userOrgRole: "User"
           // userdata data from lookup for each array
        }
    ]
  }

【问题讨论】:

    标签: node.js mongodb aggregation-framework


    【解决方案1】:

    尝试这种方式,将这些阶段添加到聚合管道。这将有助于添加用户详细信息..

     {  
           $unwind: {
                        path: "$baseData.users",
                        preserveNullAndEmptyArrays: true,
                    }, 
         },
         {
           $lookup: {
                        from: "users", // replace with your collection name
                        localField: "baseData.users.userID",
                        foreignField: "_id",
                        as: "baseData.users",
                    },
        },
        {
            $group: {
                        _id: "$_id",
                        baseData: {
                            $push: "$baseData",
                        },
                    },
        },
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-06-26
      • 2021-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多