【问题标题】:How to use $elementMatch in aggregate如何在聚合中使用 $elementMatch
【发布时间】:2020-03-10 10:36:17
【问题描述】:

如何使用child$elementMatch聚合? 我需要从 mongo 中返回这个“Grand Child”元素:productCode = "aaaa" Size = "41" and ware "LAX"

{
   "_id" : ObjectId("5db72c636309f84479ec0c80"),
   "ware" : "LAX",
   "amount" : 100
}

这是完整的对象:

{
  "_id": ObjectId("5db72c636309f84479ec0c7b"),
  "productCode": "aaaa",
  "brand": "Nike",
  "image": "some.jpg",
  "sizes": [
    {
      "_id": ObjectId("5db72c636309f84479ec0c7e"),
      "size": "41",
      "wares": [
        {
          "_id": ObjectId("5db72c636309f84479ec0c80"),
          "ware": "LAX",
          "amount": 100
        },
        {
          "_id": ObjectId("5db72c636309f84479ec0c7f"),
          "ware": "NYC",
          "amount": 7
        }
      ]
    },
    {
      "_id": ObjectId("5db72c636309f84479ec0c7c"),
      "size": "42",
      "wares": [
        {
          "_id": ObjectId("5db72c636309f84479ec0c7d"),
          "ware": "LAX",
          "amount": 16
        }
      ]
    }
  ]
}

这是我已经尝试过的,但我只是返回空数组:(

let id = "aaaa";
let size = "41";
let ware = "LAX";
Product.aggregate(
  [
    { $unwind: "$sizes.wares" },
    {
      $match: {
        productCode: id,
        "sizes.size": size,
        "sizes.wares": { $elemMatch: { ware: ware } }
      }
    }
  ],
  (err, products) => {
    if (err) {
      return res.status(422).send(err);
    }
    return res.json(products);
  }
);

【问题讨论】:

    标签: mongodb mongoose aggregation-framework aggregate


    【解决方案1】:

    您可以使用以下聚合。

    首先我们匹配 productCode,然后展开 size 和 sizes.wares,然后应用 size 和 ware 匹配,最后使用 $replaceRoot 将嵌入文档提升到根目录。

    注意:replaceRoot 适用于 MongoDb 3.4 或更高版本。

    Product.aggregate([
      {
        $match: {
          productCode: "aaaa"
        }
      },
      {
        $unwind: "$sizes"
      },
      {
        $unwind: "$sizes.wares"
      },
      {
        $match: {
          "sizes.size": "41",
          "sizes.wares.ware": "LAX"
        }
      },
      {
        $replaceRoot: {
          newRoot: "$sizes.wares"
        }
      }
    ])
    

    结果:

    [
      {
        "_id": ObjectId("5db72c636309f84479ec0c80"),
        "amount": 100,
        "ware": "LAX"
      }
    ]
    

    游乐场:

    https://mongoplayground.net/p/rD74iw76a6D

    【讨论】:

    • 该死...我在服务器上安装了 3.6.3 版本。该版本的解决方法是什么?
    • @user2544102 你能再检查一次吗?我找到了一种在你的版本中工作的方法:)
    • @user2544102 如果你也可以投票赞成答案:)
    猜你喜欢
    • 2015-04-29
    • 1970-01-01
    • 1970-01-01
    • 2015-02-27
    • 2021-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多