只能在第一个文档中更新 MongoDB 文档和添加新键?
这可以通过 MongoDB update() 轻松实现。
> db.demo162.insertOne({"StudentName":"Chris"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e3684359e4f06af551997c2")
}
> db.demo162.insertOne({"StudentName":"Bob"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e3684389e4f06af551997c3")
}
> db.demo162.insertOne({"StudentName":"David"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e36843c9e4f06af551997c4")
}借助 find() 方法从集合中显示所有文档 -
> db.demo162.find();
这将生成以下输出 -
{ "_id" : ObjectId("5e3684359e4f06af551997c2"), "StudentName" : "Chris", "StudentAge" : 23 }
{ "_id" : ObjectId("5e3684389e4f06af551997c3"), "StudentName" : "Bob" }
{ "_id" : ObjectId("5e36843c9e4f06af551997c4"), "StudentName" : "David" }以下是对文档进行更新、在第一个文档中添加新键的查询 -
> db.demo162.update({},{$set:{"StudentAge":23}},{upsert:true});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })借助 find() 方法从集合中显示所有文档 -
> db.demo162.find();
这将生成以下输出 -
{ "_id" : ObjectId("5e3684359e4f06af551997c2"), "StudentName" : "Chris", "StudentAge" : 23 }
{ "_id" : ObjectId("5e3684389e4f06af551997c3"), "StudentName" : "Bob" }
{ "_id" : ObjectId("5e36843c9e4f06af551997c4"), "StudentName" : "David" }
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP