聚合$ lookup对象数组

史努比

我有schools外地藏品groups我正在尝试$lookupusers藏品中收集文件我得到空的结果但是有一个额外的schools文件。

学校模式

const SchoolSchema = new Schema({

  groups: [
    {
      name: { type: String },
      color: { type: String },
      userDrivenName: { type: String },
    },
  ]
});

module.exports = School = mongoose.model("School", SchoolSchema);


用户架构

const UserSchema = new Schema({
    name: {
    type: String,
    required: true,
  },
  groups: [
    {
      groupId: { type: String },
      name: { type: String },
      color: { type: String },
      userDrivenName: { type: String },
    },
  ]
});

询问

db.schools.aggregate([
  {
    $match: {
      _id: ObjectId("5d836e584a24e20e6090fd7b")
    }
  },
  {
    $project: {
      groups: 1
    }
  },
  {
    $unwind: "$groups"
  },
  {
    $lookup: {
      from: "users",
      let: {
        groupId: "$groups._id"
      },
      pipeline: [
        {
          $match: {
            "groups.groupId": "$$groupId"
          }
        }
      ],
      as: "groups",

    },

  },

])

结果:

[
    {
        "_id": "5d836e584a24e20e6090fd7b",
        "groups": []
    },
    {
        "_id": "5d836e584a24e20e6090fd7b",
        "groups": []
    }
]

预期成绩:

[
   {
      "_id":"5d836e584a24e20e6090fd7b",
      "groups":[
         {
            "_id":"5ec01fdc1dfb0a4f08316dfe",
            "name":"GROUP 1",
            "users":[
               {
                  "name":"Luke Skywalker"
               }
            ]
         }
      ]
   }
]

蒙哥运动场

米克尔

两件事情:

之间存在类型不匹配groupIdgroups.groupId因此您需要使用$ toString(基于您的Mongo Playground示例),

使用自定义管道的$ lookup仅在使用$ match时才允许表达式,因此您需要$ in$ expr

{
    $lookup: {
        from: "users",
        let: { groupId: { $toString: "$groups._id" } },
        pipeline: [
            {
                $match: { 
                    $expr: {
                        $in: ["$$groupId","$groups.groupId"]
                    } 
                }
            }
        ],
        as: "groups"
    }
}

蒙哥运动场

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章