如何在 MongoDB 中使用一個命令更新並增加兩個欄位?


我們首先建立一個包含文件的集合 -

> db.incrementDemo.insertOne({"Value1":10,"Value2":20});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cbdaf07de8cc557214c0e15")
}

在集合中顯示所有文件,藉助 find() 方法。查詢如下 -

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

這將生成以下輸出 -

{
   "_id" : ObjectId("5cbdaf07de8cc557214c0e15"),
   "Value1" : 10,
   "Value2" : 20
}

以下是在 MongoDB 的一個命令中增加兩個欄位的查詢 -

> db.incrementDemo.update({},{ $inc : { Value1 : 1, Value2 : 1 } });
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

讓我們檢查兩個欄位是否都已增加 1 -

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

這將生成以下輸出 -

{
   "_id" : ObjectId("5cbdaf07de8cc557214c0e15"),
   "Value1" : 11,
   "Value2" : 21
}

更新日期: 2019 年 7 月 30 日

254 次瀏覽

開啟你的職業生涯

完成課程後獲得認證

開始
廣告
© . All rights reserved.