在MongoDB中,您可以使用聚合框架(Aggregation Framework)来对数组元素进行分组
假设您有一个名为orders
的集合,其中包含以下文档:
[
{ "_id": 1, "customer": "John", "items": ["apple", "banana", "orange"] },
{ "_id": 2, "customer": "John", "items": ["apple", "banana"] },
{ "_id": 3, "customer": "Jane", "items": ["apple", "orange"] },
{ "_id": 4, "customer": "John", "items": ["banana", "orange"] }
]
现在,您想按customer
字段对items
数组中的元素进行分组。您可以使用以下聚合查询:
db.orders.aggregate([
{ $unwind: "$items" },
{ $group: {
_id: { customer: "$customer", item: "$items" },
count: { $sum: 1 }
}},
{ $group: {
_id: "$_id.customer",
items: { $push: { item: "$_id.item", count: "$count" } },
totalCount: { $sum: "$count" }
}}
])
查询的第一个$group
阶段会按customer
和items
字段进行分组,并计算每个组的文档数量。它会推送一个包含item
和count
字段的对象到items
字段。第二个$group
阶段会按customer
字段进行分组,并将先前推送的items
字段归总为一个新的数组。
查询结果将如下所示:
[
{
"_id": "John",
"items": [
{ "item": "apple", "count": 2 },
{ "item": "banana", "count": 2 },
{ "item": "orange", "count": 2 }
],
"totalCount": 6
},
{
"_id": "Jane",
"items": [
{ "item": "apple", "count": 1 },
{ "item": "orange", "count": 1 }
],
"totalCount": 2
}
]
这个结果显示了每个客户购买的商品数量,按项目分类。
领取专属 10元无门槛券
手把手带您无忧上云