在 MongoDB 中更新并防止覆盖?
让我们创建一个包含文档的集合 -
> db.demo601.insertOne(
... {
... id:1,
... userDetails:
... {
... userName:"John",
... userMailId:"John@gmail.com"
... }
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e95ff5ced011c280a0905c7")
}
>
> db.demo601.insertOne( { id:2, userDetails: { userName:"Carol",
userMailId:"Carol@gmail.com" } } );{
"acknowledged" : true,
"insertedId" : ObjectId("5e95ff71ed011c280a0905c8")
}通过 find() 方法显示集合中的所有文档 -
> db.demo601.find();
将生成以下输出 -
{ "_id" : ObjectId("5e95ff5ced011c280a0905c7"), "id" : 1, "userDetails" : { "userName" : "John", "userMailId" : "John@gmail.com" } }
{ "_id" : ObjectId("5e95ff71ed011c280a0905c8"), "id" : 2, "userDetails" : { "userName" : "Carol", "userMailId" : "Carol@gmail.com" } }以下是用于更新的查询 -
>db.demo601.update({_id:ObjectId("5e95ff71ed011c280a0905c8")},{$set:{userMailId:"Carol@yahoo.com"}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })通过 find() 方法显示集合中的所有文档 -
> db.demo601.find();
将生成以下输出 -
{ "_id" : ObjectId("5e95ff5ced011c280a0905c7"), "id" : 1, "userDetails" :
{ "userName" : "John", "userMailId" : "John@gmail.com" }
}
{ "_id" : ObjectId("5e95ff71ed011c280a0905c8"), "id" : 2, "userDetails" :
{ "userName" : "Carol", "userMailId" : "Carol@gmail.com" }, "userMailId" : "Carol@yahoo.com"
}
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程语言
C++
C#
MongoDB
MySQL
Javascript
PHP