在MongoDB中将数组项分组并获得具有相似价格的产品计数?
要对数组项进行分组,请使用$group和$sort。让我们创建一个包含文档的集合-
> db.demo566.insertOne(
... {
...
... "ProductInformation" : [
... {
... "ProductName" : "Product-1",
... "ProductPrice" :100
... },
... {
... "ProductName" : "Product-2",
... "ProductPrice" :1100
... },
... {
... "ProductName" : "Product-3",
... "ProductPrice" :100
... },
... {
... "ProductName" : "Product-4",
... "ProductPrice" :1100
... },
... {
... "ProductName" : "Product-5",
... "ProductPrice" :100
... }
... ]
...
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e908e2339cfeaaf0b97b57a")
}在find()方法的帮助下显示集合中的所有文档-
> db.demo566.find();
这将产生以下输出-
{ "_id" : ObjectId("5e908e2339cfeaaf0b97b57a"), "ProductInformation" : [
{ "ProductName" : "Product-1", "ProductPrice" : 100 },
{ "ProductName" : "Product-2", "ProductPrice" : 1100 },
{ "ProductName" : "Product-3", "ProductPrice" : 100 },
{ "ProductName" : "Product-4", "ProductPrice" : 1100 },
{ "ProductName" : "Product-5", "ProductPrice" : 100 }
] }以下是对数组项进行分组的查询-
> db.demo566.aggregate([
... {
... "$unwind": "$ProductInformation"
... },
... {
... "$group": {
... "_id": "$ProductInformation.ProductPrice",
... "Value": { "$sum" : 1 }
... }
... },
... { "$sort": { "_id" :1 } }
... ])这将产生以下输出-
{ "_id" : 100, "Value" : 3 }
{ "_id" : 1100, "Value" : 2 }热门推荐
10 祝女儿简短祝福语大全
11 大学新年祝福语简短创意
12 元旦适合的祝福语简短
13 朋友出远门祝福语简短
14 初六简短的祝福语
15 祝男孩生日祝福语简短
16 同事调离的祝福语简短
17 拜年红包的祝福语简短
18 妈妈生日祝福语简短励志