MongoDB
 Computer >> コンピューター >  >> プログラミング >> MongoDB

MongoDBネストされたオブジェクトの値をインクリメントしますか?


ネストされたオブジェクトの値をインクリメントするには、$inc演算子を使用できます。まず、次のクエリを実装して、ドキュメントを含むコレクションを作成しましょう

>db.incrementValueDemo.insertOne({"StudentName":"Larry","StudentCountryName":"US","StudentDetails":[{"StudentSubjectName":"Math","StudentMathMarks":79}]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c986ca0330fd0aa0d2fe4a2")
}

以下は、find()メソッドを使用してコレクションからすべてのドキュメントを表示するためのクエリです

> db.incrementValueDemo.find().pretty();

これにより、次の出力が生成されます

{
   "_id" : ObjectId("5c986ca0330fd0aa0d2fe4a2"),
   "StudentName" : "Larry",
   "StudentCountryName" : "US",
   "StudentDetails" : [
      {
         "StudentSubjectName" : "Math",
         "StudentMathMarks" : 79
      }
   ]
}

以下は、ネストされたオブジェクトの値をインクリメントするためのクエリです。マークはここでインクリメントされます

> db.incrementValueDemo.update( {"StudentDetails.StudentSubjectName":"Math"}, { $inc : {
   "StudentDetails.$.StudentMathMarks" : 1 } });
   WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

以下は、値がインクリメントされているかどうかを確認するためのクエリです

> db.incrementValueDemo.find().pretty();

これにより、次の出力が生成されます

{
   "_id" : ObjectId("5c986ca0330fd0aa0d2fe4a2"),
   "StudentName" : "Larry",
   "StudentCountryName" : "US",
   "StudentDetails" : [
      {
         "StudentSubjectName" : "Math",
         "StudentMathMarks" : 80
      }
   ]
}

  1. MongoDBの配列オブジェクトを使用して配列要素の値をインクリメントします

    配列オブジェクトの値をインクリメントするには、$incを使用します。ドキュメントを使用してコレクションを作成しましょう- >db.demo506.insertOne({"details":[{id:1,Quantity:4},{id:2,Quantity:3},{id:3,Quantity:2},{id:4,Qua ntity:7}]}); {    "acknowledged" : true,    "insertedId" : ObjectId("5e882ed6987b6e

  2. MongoDBドキュメントの値を1つだけインクリメントしますか?

    単一の値のみを更新してMongoDBでインクリメントするには、update()とともに$incを使用します。ドキュメントを使用してコレクションを作成しましょう- > db.demo698.insertOne({Score:78}); {    "acknowledged" : true,    "insertedId" : ObjectId("5ea6d8a4551299a9f98c9398") } > db.demo698.insertOne({Score:56}); { &nbs