如何利用 MongoDB 嵌套 $group 和 $sum 获得具有相同 ProductID 的库存数量?
MongoDB 中的 $group 用于按指定 _id 表达式对输入文档进行分组。我们创建一个包含文档的集合 −
> db.demo466.insertOne(
... {
...
... "ProductPrice" :150,
... "ProductQuantity" : 1,
... "ProductName" : "Product-1",
... "ActualAmount" :110,
... "ProductProfit" : 40,
... "ProductId" : 1
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e80477cb0f3fa88e2279066")
}
>
> db.demo466.insertOne(
... {
...
... "ProductPrice" :150,
... "ProductQuantity" : 1,
... "ProductName" : "Product-1",
... "ActualAmount" :110,
... "ProductProfit" : 40,
... "ProductId" : 2
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e80477db0f3fa88e2279067")
}
> db.demo466.insertOne(
... {
...
... "ProductPrice" :170,
... "ProductQuantity" : 2,
... "ProductName" : "Product-2",
... "ActualAmount" :130,
... "ProductProfit" : 50,
... "ProductId" : 3
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e80477eb0f3fa88e2279068")
}使用 find() 方法显示集合中的所有文档 −
> db.demo466.find();
将生成以下输出 −
{ "_id" : ObjectId("5e80477cb0f3fa88e2279066"), "ProductPrice" : 150, "ProductQuantity" : 1,
"ProductName" : "Product-1", "ActualAmount" : 110, "ProductProfit" : 40, "ProductId" : 1 }
{ "_id" : ObjectId("5e80477db0f3fa88e2279067"), "ProductPrice" : 150, "ProductQuantity" : 1,
"ProductName" : "Product-1", "ActualAmount" : 110, "ProductProfit" : 40, "ProductId" : 2 }
{ "_id" : ObjectId("5e80477eb0f3fa88e2279068"), "ProductPrice" : 170, "ProductQuantity" : 2,
"ProductName" : "Product-2", "ActualAmount" : 130, "ProductProfit" : 50, "ProductId" : 3 }以下是 MongoDB 中使用嵌套 $group 和 $sum 的查询 −
> db.demo466.aggregate([
... {
... '$group': {
... '_id': {
... 'ProductName': '$ProductName',
... },
... 'ActualAmount': {'$sum': '$ActualAmount'},
... 'ProductQuantity': {'$sum': '$ProductQuantity'},
... 'ProductId': {'$addToSet': '$ProductId'},
... },
... },
... {
... '$project': {
... 'ProductQuantity': true,
... 'ActualAmount': true,
... 'NumberOfProductInStock': {'$size': '$ProductId'}
... }
... }])将生成以下输出 −
{ "_id" : { "ProductName" : "Product-2" }, "ActualAmount" : 130, "ProductQuantity" : 2,
"NumberOfProductInStock" : 1 }
{ "_id" : { "ProductName" : "Product-1" }, "ActualAmount" : 220, "ProductQuantity" : 2,
"NumberOfProductInStock" : 2 }
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP