配列にサブアイテムを設定するMongoDBクエリ?
位置$演算子を使用できます。まず、ドキュメントを使用してコレクションを作成しましょう-
> db.demo22.insertOne(
... {
... ProductId:101,
...
... ProductDetails:
... [
... {
... ProductFirstPrice: '35',
... ProductSecondPrice: '75'
... },
... {
... ProductFirstPrice: '',
... ProductSecondPrice:''
... },
... {
... ProductFirstPrice: '78',
... ProductSecondPrice:'24'
... }
... ]
... }
...
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e14c0b422d07d3b95082e70")
} find()メソッドを使用してコレクションからすべてのドキュメントを表示する-
> db.demo22.find().pretty();
これにより、次の出力が生成されます-
{
"_id" : ObjectId("5e14c0b422d07d3b95082e70"),
"ProductId" : 101,
"ProductDetails" : [
{
"ProductFirstPrice" : "35",
"ProductSecondPrice" : "75"
},
{
"ProductFirstPrice" : "",
"ProductSecondPrice" : ""
},
{
"ProductFirstPrice" : "78",
"ProductSecondPrice" : "24"
}
]
} 以下は、配列にサブアイテムを設定するためのMongoDBクエリです-
> db.demo22.update({ "ProductDetails.ProductFirstPrice" : "35" },
... { $set : { "ProductDetails.$.ProductFirstPrice" : "" }}, false, true);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) find()メソッドを使用してコレクションからすべてのドキュメントを表示する-
> db.demo22.find().pretty();
これにより、次の出力が生成されます-
{
"_id" : ObjectId("5e14c0b422d07d3b95082e70"),
"ProductId" : 101,
"ProductDetails" : [
{
"ProductFirstPrice" : "",
"ProductSecondPrice" : "75"
},
{
"ProductFirstPrice" : "",
"ProductSecondPrice" : ""
},
{
"ProductFirstPrice" : "78",
"ProductSecondPrice" : "24"
}
]
} -
ネストされた配列をソートするMongoDBクエリ?
MongoDBでネストされた配列を並べ替えるには、$sortを使用します。ドキュメントを使用してコレクションを作成しましょう- > db.demo505.insertOne( ... { ... "details": [ ... { ... Name:"Chris", ... "Score":58 ... }, { ... ...  
-
一意の配列アイテムを収集するためのMongoDBクエリ?
一意の配列アイテムを収集するには、distinct()を使用します。ドキュメントを使用してコレクションを作成しましょう- > db.demo588.insertOne({"CountryName":["US","AUS","UK","US","UK","AUS"]});{ "acknowledged" : true, "insertedId" : ObjectId("5e92