【问题标题】:Aggregate $lookup Array of Objects聚合 $lookup 对象数组
【发布时间】:2020-05-17 04:51:44
【问题描述】:

我有 schools 字段 groups 的集合,我正在尝试 $lookup 来自 users 集合的文档。但是,我得到的是空结果和一个额外的 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"
               }
            ]
         }
      ]
   }
]

MongoPlayground

【问题讨论】:

    标签: mongodb mongoose aggregation-framework


    【解决方案1】:

    两件事:

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

    $lookup with custom pipelines 仅在您使用 $match 时允许表达式,因此您需要 $in$expr

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

    Mongo Playground

    【讨论】:

      猜你喜欢
      • 2021-08-09
      • 2021-07-23
      • 2021-08-04
      • 1970-01-01
      • 2020-08-14
      • 1970-01-01
      • 2022-01-05
      • 2021-06-04
      相关资源
      最近更新 更多