且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

向MongoDB集合中的每个文档添加新字段

更新时间:2023-02-08 19:14:13

与更新现有集合字段相同, $set 将添加一个新字段.

Same as the updating existing collection field, $set will add a new fields if the specified field does not exist.

查看此示例:

> db.foo.find()
> db.foo.insert({"test":"a"})
> db.foo.find()
{ "_id" : ObjectId("4e93037bbf6f1dd3a0a9541a"), "test" : "a" }
> item = db.foo.findOne()
{ "_id" : ObjectId("4e93037bbf6f1dd3a0a9541a"), "test" : "a" }
> db.foo.update({"_id" :ObjectId("4e93037bbf6f1dd3a0a9541a") },{$set : {"new_field":1}})
> db.foo.find()
{ "_id" : ObjectId("4e93037bbf6f1dd3a0a9541a"), "new_field" : 1, "test" : "a" }

如果要向所有集合中添加一个new_field,则必须使用空选择器,并将multi标志设置为true(最后一个参数)以更新所有文档

In case you want to add a new_field to all your collection, you have to use empty selector, and set multi flag to true (last param) to update all the documents

db.your_collection.update(
  {},
  { $set: {"new_field": 1} },
  false,
  true
)

在上面的示例中,最后2个字段false, true指定upsertmulti标志.

In the above example last 2 fields false, true specifies the upsert and multi flags.

更新::如果设置为true,则在没有文档符合查询条件时创建一个新文档.

Upsert: If set to true, creates a new document when no document matches the query criteria.

多个::如果设置为true,则更新满足查询条件的多个文档.如果设置为false,则更新一个文档.

Multi: If set to true, updates multiple documents that meet the query criteria. If set to false, updates one document.

这是针对2.2之前的Mongo versions.对于最新版本,查询有所更改

This is for Mongo versions prior to 2.2. For latest versions the query is changed a bit

db.your_collection.update({},
                          {$set : {"new_field":1}},
                          {upsert:false,
                          multi:true})