Mongodb 聚合$lookup对象数组

Mongodb 聚合$lookup对象数组,mongodb,mongoose,aggregation-framework,Mongodb,Mongoose,Aggregation Framework,我有一个集合学校和字段组,我正在尝试从用户集合中查找$lookup文档。然而,我得到的是空的结果和一份额外的文件 学校模式 const SchoolSchema = new Schema({ groups: [ { name: { type: String }, color: { type: String }, userDrivenName: { type: String }, }, ] }); module.exports = S

我有一个集合
学校
和字段
,我正在尝试从
用户
集合中查找
$lookup
文档。然而,我得到的是空的结果和一份额外的
文件

学校模式

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 },
    },
  ]
});

用户模式

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"
               }
            ]
         }
      ]
   }
]
有两件事:

groupId
groups.groupId
之间存在类型不匹配,因此您需要使用(基于您的Mongo游乐场示例)

使用$match时仅允许表达式,因此需要和:

有两件事:

groupId
groups.groupId
之间存在类型不匹配,因此您需要使用(基于您的Mongo游乐场示例)

使用$match时仅允许表达式,因此需要和: