[英]MongoDB Group by String Field inside of an Array
I did a lot of research on MongoDB aggregation grouping, but couldn't find a solution.我对 MongoDB 聚合分组进行了大量研究,但找不到解决方案。
I have the following document structure:我有以下文档结构:
{
"_id":"6053e0ef22b8e60015a23da8",
"shoppinglist":[
{
"_id":"606ae2e34e4416001538104f",
"items":[
{
"_id":"6071c5ed8f669f0015e6eebe",
"product_id":"605852c28ea29f0015653d6f",
},
...
]
}
}
My goal is to group the items in each shopping list object using the product_id
, so that my result looks like this:我的目标是使用
product_id
对每个购物清单 object 中的项目进行分组,因此我的结果如下所示:
{
"_id":"6053e0ef22b8e60015a23da8",
"shoppinglist":[
{
"_id":"606ae2e34e4416001538104f",
"items":[
{
"_id":"6071c5ed8f669f0015e6eebe",
"product_id":"605852c28ea29f0015653d6f",
"count": 3 //3 items with the product_id = 605852c28ea29f0015653d6f
},
...
]
}
}
Can someone help me with this, I'm desperate.有人可以帮我解决这个问题,我很绝望。
$unwind
deconstruct shoppinglist
array $unwind
解构shoppinglist
清单数组$unwind
deconstruct shoppinglist.items
array $unwind
解构shoppinglist.items
数组$group
by _id
and product_id
, and get required fields using $first
and get count using $sum
$group
by _id
和product_id
,并使用$first
获取必填字段并使用$sum
获取计数$group
by _id
and shoppinglist._id
and reconstruct array of items $group
by _id
和shoppinglist._id
并重建项目数组$group
by _id
and reconstruct array of shoppinglist
$group
by _id
并重建shoppinglist
清单数组db.collection.aggregate([
{ $unwind: "$shoppinglist" },
{ $unwind: "$shoppinglist.items" },
{
$group: {
_id: {
_id: "$_id",
product_id: "$shoppinglist.items.product_id"
},
shoppinglist_id: { $first: "$shoppinglist._id" },
items_id: { $first: "$shoppinglist.items._id" },
count: { $sum: 1 }
}
},
{
$group: {
_id: {
_id: "$_id._id",
shoppinglist_id: "$shoppinglist_id"
},
items: {
$push: {
items_id: "$items_id",
product_id: "$_id.product_id",
count: "$count"
}
}
}
},
{
$group: {
_id: "$_id._id",
shoppinglist: {
$push: {
_id: "$_id.shoppinglist_id",
items: "$items"
}
}
}
}
])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.