首页 > 解决方案 > 使用嵌套文档聚合 MongoDB 数组

问题描述

我正在尝试为我的 MongoDB 数据库做顾问:

我想要做的是获取一些集成在嵌套数组中的数据,并通过其中一个嵌套键进行过滤。

该文件如下:

[
  {
    "name": "PharmaMaria",
    "country": "Spain",
    "currency": "EUR",
    "medicines": [
      {
        "name": "Medicine 1",
        "type": "Suncream",
        "price": 32,
        
      },
      {
        "name": "Medicine 2",
        "type": "Suncream",
        "price": 5
      },
      {
        "name": "Medicine 3",
        "type": "Pills",
        "price": 7
      }
    ]
  }
]

我想得到这样的过滤medicines.type

values = [
  {
    "name": "Medicine 1",
    "price": 32
  },
  {
    "name": "Medicine 2",
    "price": 5
  }
]

这是我创建的游乐场https://mongoplayground.net/p/_riatO8PKVp

谢谢!

标签: javascriptnode.jsarraysmongodbdocument

解决方案


您必须添加一个$projector$addFields阶段并使用$filter运算符将​​条件应用于每个元素。

db.collection.aggregate([
  {
    "$match": {
      "country": "Spain",
      "medicines.type": "Suncream"
    },
    
  },
  {
    "$addFields": {  // <- To add a new key
      "medicines": {  // <- Replacing existing `medicines` key
        "$filter": {  // <- Apply condition on each array elements
          "input": "$medicines",
          "as": "elem",
          "cond": {  // <- Applying match condition inside this block
            "$eq": [
              "$$elem.type",
              "Suncream"
            ],
            
          }
        }
      }
    }
  },
  
])

要仅从数组中获取特定键,请使用$map

db.collection.aggregate([
  {
    "$match": {
      "country": "Spain",
      "medicines.type": "Suncream"
    },
    
  },
  {
    "$addFields": {
      "medicines": {
        "$map": {
          "input": {
            "$filter": {
              "input": "$medicines",
              "as": "elem",
              "cond": {
                "$eq": [
                  "$$elem.type",
                  "Suncream"
                ],
                
              }
            }
          },
          "as": "med",
          "in": {
            "name": "$$med.name",
            "price": "$$med.price",
            
          }
        },
        
      }
    }
  },
  
])

以上示例 Mongo 执行

Mongo Playground 示例执行


推荐阅读