在 mongodb 中查询字典数组



我在mongodb中有一个集合db.orders,这是一个例子:

{
"_id" : ObjectId("5ed269e0f18b5c0d33150ce1"),
"user" : ObjectId("5ed16ace5b16a6100c1ae744"),
"cart" : {
"items" : [
{
"item" : {
"_id" : "5ed16847fb395528f07f2d19",
"tipo" : "anillo",
"imagePath" : "../images/anillos/anillo1.png",
"title" : "Anillo Geo",
"description" : "Anillo en bronce con baño en oro de 24k",
"price" : 25,
"qty" : 1
}
},
{
"item" : {
"_id" : "5ed16847fb395528f07f2d2e",
"tipo" : "collar",
"imagePath" : "../images/collares/collar10.png",
"title" : "Cadenita Pendulo cuarzos naturales",
"description" : "Cadenita en bronce con baño en oro de 18k.",
"price" : 20,
"qty" : 1
}
},
{
"item" : {
"_id" : "5ed16847fb395528f07f2d26",
"tipo" : "anillo",
"imagePath" : "../images/anillos/anillo14.png",
"title" : "Anillo mandala de cristales",
"description" : "Anillo en bronce con baño en oro de 24k, incluye estuche de madera ",
"price" : 20,
"qty" : 1
}
}
],
"totalQty" : 3,
"totalPrice" : 65
},
"address" : "carrera 9/ Madrid",
"city" :  "Madrid",
"name" : "Marcela R",
"paymentId" : "ch_1GoIGGByvh8EqLzfNGV02e3e",
"oderdate" : ISODate("2020-05-30T14:12:48.624Z"),
"__v" : 0
}

我需要知道有多少标题:"Anillo geo",以及通常已售出多少购物车.items.item.title。我尝试了不同的方法,但最终得到的是这样的东西:

{
"_id" : ObjectId("5ed27fee825300b7d182355d"),
"cart" : {
"items" : [
{
"title" : "Anillo Geo",
"price" : 25,
"qty" : 1,
"tipo" : "anillo"
},
{
"title" : "Cadenita Pendulo cuarzos naturales",
"price" : 29,
"qty" : 1,
"tipo" : "collar"
},
{
"title" : "Anillo mandala de cristales",
"price" : 29,
"qty" : 1, 
"tipo" : "anillo"
}
]
}
} 

但是我需要一个查询,给我这样的内容:

{"_id" : Anillo Geo, count: 5} 
{"_id" : Cadenita Pendulo cuarzos naturales, count: 8}...

有人知道如何进行此查询吗? 亲切问候!!

基本上,您需要在_id + title上展开cart.items数组和组,以计算_id文档重复的标题。

db.collection.aggregate([
{
$unwind: "$cart.items"
},
{
$group: {
_id: { _id: "$_id", title: "$cart.items.item.title" },
count: { $sum: 1 }
}
},
/** transform fields the way you want in output */
{
$project: { _id: "$_id._id", title: "$_id.title", count: 1 }
}
])

测试:蒙古游乐场

注意:

如果可能的话,尝试使用$match作为第一阶段,在单个文档上执行此操作,即单个用户或至少较小的文档,而不是整个集合。

最新更新