首页 > 解决方案 > 如何对外键进行条件聚合查找

问题描述

经过多次尝试,我无法对我的集合进行良好的条件聚合。

我使用两个集合:

评论集合的比赛

我只需要为我的第二个管道获取已发布的评论。我不想使用$project. 可以只使用$match吗?当我使用 localField、foreignField 时,效果很好,但我只需要过滤已发布的评论。我为此苦苦挣扎,我不明白为什么let不给我foreignKey。我试过: _id, $reviews, 等等..

我的$lookup样子是这样的:

{
    $lookup: {
      from: "reviews",
      as: "reviews",
      let: { reviewsId: "$_id" },
      pipeline: [
        {
          $match: {
            $expr: {
              $and: [
                // If I comment the next line, it give all the reviews to all the races
                { $eq: ["$_id", "$$reviewsId"] },
                { $eq: ["$is_published", true] }
              ]
            }
          }
        }
      ]

      // localField: "reviews",
      // foreignField: "_id"
    }
  },

比赛示例:

{  
   "description":"Nice race",
   "attendees":[  

   ],
   "reviews":[  
      {  
         "$oid":"5c363ddcfdab6f1d822d7761"
      },
      {  
         "$oid":"5cbc835926fa61bd4349a02a"
      }
   ],
   ...
}

评论示例:

{  
   "_id":"5c3630ac5d00d1dc26273dab",
   "user_id":"5be89576a38d2b260bfc1bfe",
   "user_pseudo":"gracias",
   "is_published":true,
   "likes":[],
   "title":"Best race",
   "__v":10,
   ...
}

我很快就会发疯:'(......如何做到这一点?

标签: node.jsmongodbaggregation-framework

解决方案


首先,您必须采用正确的字段才能从引用的集合中获取数据,即reviews. 其次,您需要使用$in聚合运算符,因为您的reviews字段是一个ObjectIds 数组。

db.getCollection('races').aggregate([
  { "$lookup": {
    "from": "reviews",
    "let": { "reviews": "$reviews" },
    "pipeline": [
      { "$match": {
        "$expr": { "$in": [ "$_id", "$$reviews" ] },
        "is_published": true
      }}
    ],
    "as": "reviews"
  }}
])

推荐阅读