【问题标题】:mongoose: filtering $lookup in aggregation猫鼬:在聚合中过滤 $lookup
【发布时间】:2019-08-02 22:05:41
【问题描述】:

我在猫鼬中有以下聚合代码,它运行良好,但我正在寻找过滤结果:

Mov.aggregate(
       [
              { $sort: { _id: 1, car_id: 1, area: 1 } },
         {
           $group:
             {
               _id: "$car_id",
               lastLocation: { $last: "$area" }
             }
         },
                     {
            $lookup: {
                from: Car.collection.name,
                "localField": "_id",
                "foreignField": "_id",
                as: 'cars'
            }
        },    
      ]
         )
        .then(movs => {
            res.send(movs);
        }).catch(err => {
            res.status(500).send({
                message: err.message
            });
 });

如何过滤$lookup 中的Car.collection.name,我只想获得带有{"active":true} 的汽车?

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    您可以使用不同的查找策略。以下是更新后的查询:

    Mov.aggregate([{
        $sort: {
          "_id": 1,
          "car_id": 1,
          "area": 1
        }
      },
      {
        $group: {
          _id: "$car_id",
          lastLocation: {
            $last: "$area"
          }
        }
      },
      {
        $lookup: {
          from: Car.collection.name,
          let: {
            "_id": "$_id"
          },
          pipeline: [{
            $match: {
              $expr: {
                $eq: ["$_id", "$$_id"]
              },
              active: true
            }
          }],
          "as": "cars"
        }
      }
    ]).then(movs => {
      res.send(movs);
    }).catch(err => {
      res.status(500).send({
        message: err.message
      });
    });
    

    您可以查看以下链接以获取有关此查找策略https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/的更多信息

    【讨论】:

    • 我得到 {"message":"arguments to $lookup must be strings, let: { _id: \"$_id\" } is type object"}
    • @Hisham 您使用的是哪个 mongo 版本?
    • v3.4.7,如果我的mongodb当前版本中查找语法没有解决方案,我想我必须升级到v3.6
    • 是的,您甚至应该升级到 v3.6 而不是 v4.0 以获得一些更酷的功能:)
    猜你喜欢
    • 2020-02-10
    • 2016-07-27
    • 2021-12-07
    • 2021-01-18
    • 2021-07-18
    • 2019-01-30
    • 1970-01-01
    • 2016-12-19
    • 2015-05-19
    相关资源
    最近更新 更多