要增加MongoDB中的字段,可以使用$inc运算符。首先让我们创建一个包含文档的集合-
> db.incrementDemo.insertOne({"PlayerScore":100}); { "acknowledged" : true, "insertedId" : ObjectId("5cc81cdd8f9e6ff3eb0ce44e") } > db.incrementDemo.insertOne({"PlayerScore":290}); { "acknowledged" : true, "insertedId" : ObjectId("5cc81ce28f9e6ff3eb0ce44f") } > db.incrementDemo.insertOne({"PlayerScore":560}); { "acknowledged" : true, "insertedId" : ObjectId("5cc81ce68f9e6ff3eb0ce450") }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.incrementDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5cc81cdd8f9e6ff3eb0ce44e"), "PlayerScore" : 100 } { "_id" : ObjectId("5cc81ce28f9e6ff3eb0ce44f"), "PlayerScore" : 290 } { "_id" : ObjectId("5cc81ce68f9e6ff3eb0ce450"), "PlayerScore" : 560 }
以下是增加MongoDB中的字段的查询-
> db.incrementDemo.update({ _id:ObjectId("5cc81ce28f9e6ff3eb0ce44f") },{ $inc: {"PlayerScore":10 }}); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
在上面的查询中,我将值290递增为值10-
> db.incrementDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5cc81cdd8f9e6ff3eb0ce44e"), "PlayerScore" : 100 } { "_id" : ObjectId("5cc81ce28f9e6ff3eb0ce44f"), "PlayerScore" : 300 } { "_id" : ObjectId("5cc81ce68f9e6ff3eb0ce450"), "PlayerScore" : 560 }