如何在 MongoDB 中設定 $inc 的限制?


若要設定 $inc 的限制,請使用以下語法 −

db.yourCollectionName.update({yourFieldName : {$lt : yourValue}}, {$inc : {yourFieldName : yourIncrementValue}},false,true);

我們首先使用文件建立一個集合 −

> db.limitIncrementDemo.insertOne({"StudentId":101,"StudentScore":95});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd2ce9eb64f4b851c3a13c3")
}
> db.limitIncrementDemo.insertOne({"StudentId":102,"StudentScore":55});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd2cea0b64f4b851c3a13c4")
}
> db.limitIncrementDemo.insertOne({"StudentId":103,"StudentScore":67});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd2cea1b64f4b851c3a13c5")
}
> db.limitIncrementDemo.insertOne({"StudentId":104,"StudentScore":56});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd2cea3b64f4b851c3a13c6")
}
> db.limitIncrementDemo.insertOne({"StudentId":105,"StudentScore":79});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd2cea4b64f4b851c3a13c7")
}

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

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

這將產生以下輸出 −

{
   "_id" : ObjectId("5cd2ce9eb64f4b851c3a13c3"),
   "StudentId" : 101,
   "StudentScore" : 95
}
{
   "_id" : ObjectId("5cd2cea0b64f4b851c3a13c4"),
   "StudentId" : 102,
   "StudentScore" : 55
}
{
   "_id" : ObjectId("5cd2cea1b64f4b851c3a13c5"),
   "StudentId" : 103,
   "StudentScore" : 67
}
{
   "_id" : ObjectId("5cd2cea3b64f4b851c3a13c6"),
   "StudentId" : 104,
   "StudentScore" : 56
}
{
   "_id" : ObjectId("5cd2cea4b64f4b851c3a13c7"),
   "StudentId" : 105,
   "StudentScore" : 79
}

以下是設定 $inc 限制的查詢 −

> db.limitIncrementDemo.update({StudentScore : {$lt : 75}}, {$inc : {StudentScore : 10}},false,true);
WriteResult({ "nMatched" : 3, "nUpserted" : 0, "nModified" : 3 })

讓我們檢查上述集合中的所有文件 −

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

這將產生以下輸出 −

{
   "_id" : ObjectId("5cd2ce9eb64f4b851c3a13c3"),
   "StudentId" : 101,
   "StudentScore" : 95
}
{
   "_id" : ObjectId("5cd2cea0b64f4b851c3a13c4"),
   "StudentId" : 102,
   "StudentScore" : 65
}
{
   "_id" : ObjectId("5cd2cea1b64f4b851c3a13c5"),
   "StudentId" : 103,
   "StudentScore" : 77
}
{
   "_id" : ObjectId("5cd2cea3b64f4b851c3a13c6"),
   "StudentId" : 104,
   "StudentScore" : 66
}
{
   "_id" : ObjectId("5cd2cea4b64f4b851c3a13c7"),
   "StudentId" : 105,
   "StudentScore" : 79
}

更新於: 2019 年 7 月 30 日

222 次瀏覽

啟動你的 職業生涯

完成課程,獲得認證

開始
廣告