如何使用 mongoose 通过匹配对象数组中的值来聚合 mongodb 数据?

问题描述 投票:0回答:1

嗨,我在 mongodb 中有以下数据

{"items": [
    {
      "_id": {
        "$oid": "64ca1731c60c5e5380bb8ae1"
      },
      "item_id": "ITEM_004",
      "title": "Sampoo",
      "quantity": 3,
      "barcode": "BV004",
      "msrp": 12,
      "offerPrice": 7,
      "taxCode": "string",
      "taxRate": 8.25,
      "item_image": "string",
      "subtotal": 21,
      "total": 22.74,
      "tax": 1.74,
      "discount": 15
    },
    {
      "_id": {
        "$oid": "64ca1731c60c5e5380bb8ae2"
      },
      "item_id": "ITEM_006",
      "title": "Laptop",
      "quantity": 1,
      "barcode": "BV006",
      "msrp": 52,
      "offerPrice": 52,
      "taxCode": "string",
      "taxRate": 0,
      "item_image": "string",
      "subtotal": 52,
      "total": 52,
      "tax": 0,
      "discount": 0
    }
  ]}

我有一个要求,我必须匹配 items.tax >0 并显示

以下是我尝试过的聚合

model.aggregate([
          {
            $match: {
              item: {
                $elemMatch: {
                  tax: { $gt: 0 }
                }
              }
            }
          },
          { $group: { _id: null, count: { $sum: 1 } } }
        ])

但这似乎给了我空值,请让我知道如何进一步进行

node.js mongodb object mongoose aggregate
1个回答
0
投票

您的聚合正在查找名为“item”的嵌套元素,而您的文档中没有该元素。我认为你真正需要的是更简单一点:

model.aggregate([
  {
    $match: {
       tax: { $gt: 0 }
    }
  },
  { $group: { _id: null, count: { $sum: 1 } } }
])

您可以在此处获取更多信息:https://www.mongodb.com/docs/manual/reference/operator/aggregation/match/#examples

© www.soinside.com 2019 - 2024. All rights reserved.