在 MongoDB 中使用搜索条件更新最后一行?
要使用搜索条件更新,请在 MongoDB 中使用 findAndModify()。让我们创建一个包含文档的集合 -
> 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 }
广告