【问题标题】:Mongo DB filter on other collection without projecting any fields from foreign collectionMongodb 在其他集合上过滤,而不从外国集合中投影任何字段
【发布时间】:2021-02-09 05:05:03
【问题描述】:

用户收藏

{
   "_id: : "123"
   "name" : "John Doe",
   "age"  : 40,
}

审计收集

{
  "_id" : "456",
  "region": "IND"
  "userId" : 123
}

我需要对“区域”为“IND”的用户集合执行聚合,但不希望投影来自外部集合的字段。到目前为止,我尝试的是如下查找

db.User.aggregate([
{
   $lookup:
     {
       from: "Audit",
       localField: "_id",
       foreignField: "userId",
       as: "auditTrail"
     }
},
{
    $unwind: "$auditTrail"
},
{
    $match : {
            "auditTrail.region": "IND"
        }
}, 
{
   $project : {"auditTrail.region": 0}
}
])

另一种方法是使用管道查找而不投影外部字段

db.User.aggregate([
   {
      $lookup:
         {
           from: "Audit",
           let: { user_id: "$_id"},
           pipeline: [
              { $match:
                 { $expr:
                    { $and:
                       [
                         { $eq: [ "$userId",  "$$user_id" ] }
                       ]
                    }
                 }
              },
              { $project: { _id: 1} }
           ],
           as: "stockdata"
         }
    }
])

这里提到的两个集合都是简化的,在生产中可以是一个巨大的文档,每个集合中有数千条记录,除了过滤外国集合之外,还可以有匹配阶段来过滤源集合中的字段。有没有更好的方法来做到这一点?

【问题讨论】:

    标签: mongodb mongodb-query aggregation-framework


    【解决方案1】:

    您可以通过在$match$lookup 管道中添加区域条件来修改您的第二个查询。

    db.User.aggregate([
       {
          $lookup:
             {
               from: "Audit",
               let: { user_id: "$_id"},
               pipeline: [
                  { $match:
                     { $expr:
                        { $and:
                           [
                             { $eq: [ "$userId", "$$user_id" ] },
                             { $eq: [ "$region", "IND" ] }  // region Condition added
                           ]
                        }
                     }
                  },
                  { $project: { _id: 1} }
               ],
               as: "stockdata"
             }
        }
    ])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-26
      • 2016-02-25
      • 2015-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多