增加嵌入了 MongoDB 文件中的欄位?


假設,這裡我們在位於 StudentDetails 中的 MongoDB 中對 StudentScores 進行增量 −

... "StudentScores": {
...    "StudentMathScore": 90,
...    "StudentMongoDBScore": 78
... }

讓我們先使用文件建立集合 −

> db.embeddedValueIncrementDemo.insertOne(
...    {
...       "StudentDetails": {
...          "StudentScores": {
...             "StudentMathScore": 90,
...             "StudentMongoDBScore": 78
...          }
...       }
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd2b670345990cee87fd896")
}

以下是在 find() 方法的幫助下顯示集合中的所有文件的查詢 −

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

這將產生以下輸出 −

{
   "_id" : ObjectId("5cd2b670345990cee87fd896"),
   "StudentDetails" : {
      "StudentScores" : {
         "StudentMathScore" : 90,
         "StudentMongoDBScore" : 78
      }
   }
}

以下是對嵌入值進行增量的查詢。這裡,我們對 StudentMongoDBScore 進行增量 −

> db.embeddedValueIncrementDemo.update({ _id: new ObjectId("5cd2b670345990cee87fd896") }, { $inc: { "StudentDetails.StudentScores.StudentMongoDBScore": 20 } }, { upsert: true, safe: true }, null);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

再一次檢視所有文件 −

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

這將產生以下輸出 −

{
   "_id" : ObjectId("5cd2b670345990cee87fd896"),
   "StudentDetails" : {
      "StudentScores" : {
         "StudentMathScore" : 90,
         "StudentMongoDBScore" : 98
      }
   }
}

更新日期:30-7-2019

143 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.