如何在 MongoDB 中仅更新一个属性?
要仅更新一个属性,请在 MongoDB 中使用 $addToSet。让我们创建一个含文档的集合 −
> db.demo336.insertOne({"Name":"Chris","Score":[45,67,78]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e522cb1f8647eb59e562097")
}
> db.demo336.insertOne({"Name":"David","Score":[89,93,47]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e522cb2f8647eb59e562098")
}在集合的帮助下显示所有文档的查找方法 −
> db.demo336.find();
这将产生以下输出 −
{ "_id" : ObjectId("5e522cb1f8647eb59e562097"), "Name" : "Chris", "Score" : [ 45, 67, 78 ] }
{ "_id" : ObjectId("5e522cb2f8647eb59e562098"), "Name" : "David", "Score" : [ 89, 93, 47 ] }以下是仅在 MongoDB 中更新一个属性的查询 −
> db.demo336.update({Name:"David"},{ $addToSet: {Score: [56,34,71] }});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })在集合的帮助下显示所有文档的查找方法 −
> db.demo336.find();
这将产生以下输出 −
{ "_id" : ObjectId("5e522cb1f8647eb59e562097"), "Name" : "Chris", "Score" : [ 45, 67, 78 ] }
{ "_id" : ObjectId("5e522cb2f8647eb59e562098"), "Name" : "David", "Score" : [ 89, 93, 47, [ 56, 34, 71 ] ] }
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程语言
C++
C#
MongoDB
MySQL
Javascript
PHP