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 } -
IDを並べ替え、MongoDBでアイテムを逆にします
$ naturalは、ドキュメントを自然な順序で返します。アイテムを元に戻すには、 $ natural:-1を使用します 。ドキュメントを使用してコレクションを作成しましょう- > db.demo710.insertOne({id:101,Name:"Robert"}); { "acknowledged" : true, "insertedId" : ObjectId("5ea83a855d33e20ed1097b7a") } > db.demo710
-
ドキュメント内の配列アイテムの数をカウントし、新しいフィールドに表示するMongoDBクエリ
ドキュメント内の配列アイテムの数をカウントするには、MongoDBで$sizeを使用します。ドキュメントを使用してコレクションを作成しましょう- > db.demo703.insertOne({"ListOfSubject":["MySQL","MongoDB"]}); { "acknowledged" : true, "insertedId" : ObjectId("5ea6ebaf551299a9f98c93b4"