通过 mongoDB 查询将响应转换为对象数组

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

我在 mongoDB 中编写了一个简单的查询并获取与产品 id 相关的所有数据。现在我想将我的响应转换为对象数组。请看下面。

查询:

db.collection.find({ "product_id": 1212 })

得到回应:

[
  {
    "product_id": 1212,
    "name": "sprit",
    "category_id": 1234,
    "category": "drink"
  },
  {
    "product_id": 1212,
    "name": "sprit",
    "category_id": 2122,
    "category": "soda"
  },
  {
    "product_id": 1212,
    "name": "sprit",
    "category_id": 2121,
    "category": "mocktail"
  },
  {
    "product_id": 1212,
    "name": "sprit",
    "category_id": 2121,
    "category": "mocktail"
  }
]

我想通过 MongoDB 查询将相同的数据转换为不同的格式,并删除重复的类别 id。

所需回应:

[
  {
    "product_id": 1212,
    "name": "sprit",
    "categogies": [
      {
        "category_id": 1234,
        "category": "drink"
      },
      {
        "category_id": 2122,
        "category": "soda"
      },
      {
        "category_id": 2121,
        "category": "mocktail"
      }
    ]
  ]
arrays mongodb
1个回答
0
投票

通过

product_id
$group
进行分组,并通过
categogies
将不同文档添加到
$addToSet
数组中。

db.collection.aggregate([
  {
    $match: {
      "product_id": 1212
    }
  },
  {
    $group: {
      _id: "$product_id",
      name: {
        $first: "$name"
      },
      categogies: {
        $addToSet: {
          "category_id": "$category_id",
          "category": "$category"
        }
      }
    }
  },
  {
    $project: {
      _id: 0,
      product_id: "$_id",
      name: "$name",
      categogies: "$categogies"
    }
  }
])

演示@Mongo Playground

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