使用mongodb聚合从嵌套在数组中的对象获取字段

68bkxrlz  于 2023-02-03  发布在  Go
关注(0)|答案(1)|浏览(144)

嗨,我有数组字段在我的文档中,像这样:

{
    otherFields....,
    "SlsIvcDtls": [
        {
            "_t": [
                "LocalSalesInvoiceDocumentDetailModel",
                "LocalSalesInvoiceDocumentGoodsServiceDetailModel",
                "LocalSalesInvoiceDocumentGoodsDetailModel"
            ],
            "_id": "e4dc3121-9ef7-4eef-ba60-a76a96882269",
            "Type": null,
            "Dsc": "￘쁴フ￘ᄄ ￘ᄇ￙ナᅴフ￙ニᅴフ",
            "IsAuto": false,
            "IdGds": 1141601,
>!          "Amount": "1", //I want this field
            "Price": "1520000",//I want and this field
            "DiscountAmount": "0",
            "DiscountPercent": "0",
            "ExtraAmount": "0",
            "ExtraPercent": "0",
            "TaxAmount": "0",
            "IsAutoDiscount": false,
            "IsAutoExtra": false,
            "IdInv": null,
            "IdPrs": null,
            "IdUnt": null
        }
    ],
}

我想访问金额和价格领域与我的$项目在聚合框架,请帮助我槽。

w8ntj3qf

w8ntj3qf1#

您可以使用简单的$project操作符来完成此操作,为每个要保留的字段指定1
例如:

db.SlsIvcDtls.aggregate([
  {
    "$project": {
      "Amount": 1,
      "Price": 1,
    }
  }
])

你可以在蒙戈Playground看到:https://mongoplayground.net/p/aLxBZAAPCr5
默认情况下,$project运算符将保留_id字段。如果要删除它,可以按如下所示更改查询:

db.SlsIvcDtls.aggregate([
  {
    "$project": {
      "Amount": 1,
      "Price": 1,
      "_id" : 0,
    }
  }
])

相关问题