javascript 如何在MongoDb中使用$lookup及其管道在查找字段中添加localField

hkmswyz6  于 2023-05-16  发布在  Java
关注(0)|答案(1)|浏览(93)

我想知道如何使用$lookup和pipeline将**localField添加到lookup field中。
因此,我有一个
user模式,如下所示(我希望在最终结果中保留"added_at"**字段)

User {
   _id: ObjectId("123456789xx")
   first_name: "Sam",
   last_name: "Jones",
   email: "samjones@gmail.com",
   inbox: [
      {
          participant: ObjectId("1XXXXXXXXX"),
          added_at: "12:00:00 09/21/2021"
      },
      {
          participant: ObjectId("2XXXXXXXXX"),
          added_at: "12:00:00 11/21/2022"
      },
   ]
}

现在我使用$lookup填充**participant**字段

{
   from: "Users",
   localField: "inbox.participant",
   foreignField:"_id",
   as: "participants",
   pipeline:[
      { $project: {first_name:1, last_name:1, _id: 1}}
   ]
}

然后我得到:

{
  _id: ObjectId("123456789xx")
  first_name: "Sam",
  last_name: "Jones",
  email: "samjones@gmail.com",
  inbox:...,
  participants: [
     { _id: ObjectId("1xxxxx"), first_name: "John", last_name:"Doe"},
     { _id: ObjectId("2xxxxx"), first_name: "Jack", last_name: "Smith"}
  ]
}

我希望能够在每个参与者中保留**"added_at"**字段,如何才能做到这一点?
谢谢

xam8gpfp

xam8gpfp1#

一个选项是添加另一个$set步骤:

db.Users.aggregate([
  {$lookup: {
      from: "Users",
      localField: "inbox.participant",
      foreignField: "_id",
      as: "participants",
      pipeline: [{$project: {first_name: 1, last_name: 1, _id: 1}}]
  }},
  {$set: {
      participants: {$map: {
          input: "$participants",
          in: {$mergeObjects: [
              "$$this",
              {added_at: {$arrayElemAt: [
                    "$inbox.added_at",
                    {$indexOfArray: ["$inbox.participant", "$$this._id"]}
              ]}}
          ]}
      }}
  }}
])

了解它在playground example上的工作原理

相关问题