使用MongoDB嵌套的$ group和$ sum获取具有相似ProductID的股票数量?
> 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 }热门推荐
1 狗狗技能训练
5 如何训练狗狗笑
6 狗狗训练排便
9 狗狗响片训练
10 如何训练狗狗不捡食
11 狗狗尿训练
12 怎么训练狗狗找东西
13 狗狗训练站立
14 狗狗训练飞盘
15 鞍山狗狗训练
16 怎样训练泰迪狗狗谢谢
17 狗狗外出训练
18 怎么训练金毛狗狗大小便