mongodb聚合以过滤聚合字段中的关系

时间:2020-07-18 09:23:04

标签: mongodb mongodb-query aggregation-framework

我有一个Transaction这样的收藏集:

{
  _id: ObjectId("5f1284078a7dd8a6b9140c97")
  company: ObjectId("5f127ce1e354f37df698f55e")
  person: ObjectId("5f1284078a7dd8a6b9140c95")
  actionTransaction: "Purchase"
}

Companies收集示例:

{
  _id: ObjectId("5f127ce1e354f37df698f55e")
  name:  "MongoDB Inc"
  phoneNumber: "+1111111111"
  members: [
              {
                  _id: ObjectId("5f1284078a7dd8a6b9140c95")
                  title: "CEO"
                  role: "ADMIN"
              },
              {
                  _id: ObjectId("5f1284078a7ff8a6b9300d93")
                  title: "CHAIRMAN"
                  role: "Others"
              }
          ]
}

People收集示例:

{
   _id: ObjectId("5f1284078a7dd8a6b9140c95")
   name: "Foo Bar"
   gender: "Male"
}

然后我要在聚合上设置一个新字段,称为personData的新字段,该字段过滤与{Transaction“集合中的company.members._id相等的person,并且对于这种情况下,我这样查询

db.transaction.aggregate(
 [

   { 
     $lookup: 
        {
            from: "companies",
            localField: "company",
            foreignField: "_id",
            as, "company"
        }
   },
   { $unwind: "$company" },
   {
     $set: {
        "personData": {
           $filter: {
              input: "$company.members"
              as: "theMembers"
              cond: {
                   { $eq : ["$$theMembers._id", "$person"]}
              }
           }
        }
      }
   }
 ]
)

personData总是在这里为我返回空数组,这是查询的想法吗?我已经寻找了整整一天,但找不到任何有效的方法,并尝试了以上,希望这有意义

谢谢

0 个答案:

没有答案