使用MongoDB中的搜索条件更新最后一行?
要更新搜索条件,请findAndModify()
在MongoDB中使用。让我们创建一个包含文档的集合-
> db.demo516.insertOne({"Name":"John","Age":22,"Score":56});{"acknowledged" : true,
"insertedId" : ObjectId("5e889fdb987b6e0e9d18f591")
}
> db.demo516.insertOne({"Name":"John","Age":23,"Score":67});{
"acknowledged" : true,
"insertedId" : ObjectId("5e889ff1987b6e0e9d18f592")
}
> db.demo516.insertOne({"Name":"John","Age":22,"Score":56});{
"acknowledged" : true,
"insertedId" : ObjectId("5e889ff3987b6e0e9d18f593")
}
> db.demo516.insertOne({"Name":"John","Age":22,"Score":66});{
"acknowledged" : true,
"insertedId" : ObjectId("5e889ffa987b6e0e9d18f594")
}
在find()
方法的帮助下显示集合中的所有文档-
> db.demo516.find();
这将产生以下输出-
{ "_id" : ObjectId("5e889fdb987b6e0e9d18f591"), "Name" : "John", "Age" : 22, "Score" : 56 }{ "_id" : ObjectId("5e889ff1987b6e0e9d18f592"), "Name" : "John", "Age" : 23, "Score" : 67 }
{ "_id" : ObjectId("5e889ff3987b6e0e9d18f593"), "Name" : "John", "Age" : 22, "Score" : 56 }
{ "_id" : ObjectId("5e889ffa987b6e0e9d18f594"), "Name" : "John", "Age" : 22, "Score" : 66 }
以下是使用MongoDB中的搜索条件更新最后一行的查询-
> db.demo516.findAndModify({... query: {Name: "John", Age: 22},
... sort: {_id: -1},
... update: {$set: {Score: 98}},
... new: true
... })
{
"_id" : ObjectId("5e889ffa987b6e0e9d18f594"),
"Name" : "John",
"Age" : 22,
"Score" : 98
}
在find()
方法的帮助下显示集合中的所有文档-
> db.demo516.find();
这将产生以下输出-
{ "_id" : ObjectId("5e889fdb987b6e0e9d18f591"), "Name" : "John", "Age" : 22, "Score" : 56 }{ "_id" : ObjectId("5e889ff1987b6e0e9d18f592"), "Name" : "John", "Age" : 23, "Score" : 67 }
{ "_id" : ObjectId("5e889ff3987b6e0e9d18f593"), "Name" : "John", "Age" : 22, "Score" : 56 }
{ "_id" : ObjectId("5e889ffa987b6e0e9d18f594"), "Name" : "John", "Age" : 22, "Score" : 98 }
以上是 使用MongoDB中的搜索条件更新最后一行? 的全部内容, 来源链接: utcz.com/z/343368.html