MongoDB文档中如何递增单个值
要仅更新单个值并在MongoDB中对其进行递增,请使用$inc和update()。让我们创建一个包含文档的集合-
> db.demo698.insertOne({Score:78});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ea6d8a4551299a9f98c9398")
}
> db.demo698.insertOne({Score:56});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ea6d8a7551299a9f98c9399")
}
> db.demo698.insertOne({Score:65});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ea6d8aa551299a9f98c939a")
}
> db.demo698.insertOne({Score:88});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ea6d8b0551299a9f98c939b")
}在find()方法的帮助下显示集合中的所有文档-
> db.demo698.find();
这将产生以下输出-
{ "_id" : ObjectId("5ea6d8a4551299a9f98c9398"), "Score" : 78 }
{ "_id" : ObjectId("5ea6d8a7551299a9f98c9399"), "Score" : 56 }
{ "_id" : ObjectId("5ea6d8aa551299a9f98c939a"), "Score" : 65 }
{ "_id" : ObjectId("5ea6d8b0551299a9f98c939b"), "Score" : 88 }以下是仅增加单个值的查询-
> db.demo698.update({_id:ObjectId("5ea6d8b0551299a9f98c939b")},{$inc:{Score:12}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })在find()方法的帮助下显示集合中的所有文档-
> db.demo698.find();
这将产生以下输出-
{ "_id" : ObjectId("5ea6d8a4551299a9f98c9398"), "Score" : 78 }
{ "_id" : ObjectId("5ea6d8a7551299a9f98c9399"), "Score" : 56 }
{ "_id" : ObjectId("5ea6d8aa551299a9f98c939a"), "Score" : 65 }
{ "_id" : ObjectId("5ea6d8b0551299a9f98c939b"), "Score" : 100 }热门推荐
10 小红书平安祝福语简短
11 生日祝福语大全女孩简短
12 收生日红包祝福语 简短
13 领证幽默祝福语简短
14 法考面试祝福语简短
15 老哥出门祝福语简短语
16 送灯祝福语简短独特
17 幼儿狗年祝福语大全简短
18 好听的元旦简短祝福语