MongoDBネストされた配列内の値をインクリメントしますか?
これには、位置演算子$を使用できます。上記の概念を理解するために、ドキュメントを使用してコレクションを作成しましょう。ドキュメントを使用してコレクションを作成するためのクエリは次のとおりです-
> db.incrementValueInNestedArrayDemo.insertOne(
... {"UniqueId":1,
... "StudentDetails":
... [
... {
... "StudentId":101,
... "StudentMarks":97
... },
... {
... "StudentId":103,
... "StudentMarks":99
... },
... {
... "StudentId":105,
... "StudentMarks":69
... },
... {
... "StudentId":107,
... "StudentMarks":59
... }
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5c77dd71fc4e719b197a12f7")
} find()メソッドを使用して、コレクションのすべてのドキュメントを表示します。クエリは次のとおりです-
> db.incrementValueInNestedArrayDemo.find().pretty();
以下は出力です-
{
"_id" : ObjectId("5c77dd71fc4e719b197a12f7"),
"UniqueId" : 1,
"StudentDetails" : [
{
"StudentId" : 101,
"StudentMarks" : 97
},
{
"StudentId" : 103,
"StudentMarks" : 99
},
{
"StudentId" : 105,
"StudentMarks" : 92
},
{
"StudentId" : 107,
"StudentMarks" : 59
}
]
} ネストされた配列の値をインクリメントするクエリは次のとおりです-
> db.incrementValueInNestedArrayDemo.update({UniqueId:1,"StudentDetails.StudentId":107},
{$inc:{"StudentDetails.$.StudentMarks":1}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) StudentId 107-
を使用して、ネストされた配列の値が上記のコレクションでインクリメントされているかどうかを確認しましょう。> db.incrementValueInNestedArrayDemo.find().pretty();
以下は出力です-
{
"_id" : ObjectId("5c77dd71fc4e719b197a12f7"),
"UniqueId" : 1,
"StudentDetails" :
[
{
"StudentId" : 101,
"StudentMarks" : 97
},
{
"StudentId" : 103,
"StudentMarks" : 99
},
{
"StudentId" : 105,
"StudentMarks" : 92
},
{
"StudentId" : 107,
"StudentMarks" : 60
}
]
} サンプル出力を見ると、フィールド名「StudentMarks」が59から60に更新されています。これは、1ずつ増加することを意味します。
-
ネストされた配列をソートするMongoDBクエリ?
MongoDBでネストされた配列を並べ替えるには、$sortを使用します。ドキュメントを使用してコレクションを作成しましょう- > db.demo505.insertOne( ... { ... "details": [ ... { ... Name:"Chris", ... "Score":58 ... }, { ... ...  
-
MongoDBコレクションを配列値で並べ替えますか?
MongoDBコレクションを配列値で並べ替えるには、$ sortとともにaggregate()を使用します。ドキュメントを使用してコレクションを作成しましょう- > db.demo577.insertOne( ... { ... ... "student": { ... "details": [ ... { ... &