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 } -
IDを並べ替え、MongoDBでアイテムを逆にします
$ naturalは、ドキュメントを自然な順序で返します。アイテムを元に戻すには、 $ natural:-1を使用します 。ドキュメントを使用してコレクションを作成しましょう- > db.demo710.insertOne({id:101,Name:"Robert"}); { "acknowledged" : true, "insertedId" : ObjectId("5ea83a855d33e20ed1097b7a") } > db.demo710
-
MongoDBの「$group」操作の最初の2つのフィールドのみを並べ替えて取得します
ドキュメントを使用してコレクションを作成しましょう- > db.demo576.insertOne({id:101,Name:"Chris",Marks:45}){ "acknowledged" : true, "insertedId" : ObjectId("5e916c3b581e9acd78b427fa") } > db.demo576.insertOne({id:101,Name:"John",Marks:55}){ &qu