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

  • Post author:
  • Post category:其他


本文翻译自:

Add new field to every document in a MongoDB collection


How can I add a new field to every document in an existent collection?


如何为现有集合中的每个文档添加新字段?


I know how to update an existing document’s field but not how to add a new field to every document in a collection.


我知道如何更新现有文档的字段,但不知道如何向集合中的每个文档添加新字段。


How can I do this in the

mongo

shell?


我怎么能在

mongo

shell中做到这一点?


#1楼

参考:

https://stackoom.com/question/WMoq/将新字段添加到MongoDB集合中的每个文档


#2楼


Same as the updating existing collection field,


$set


will add a new fields if the specified field does not exist.


与更新现有集合字段相同,如果指定的字段不存在,


$set


将添加新字段。


Check out this example:


看看这个例子:

> 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" }



EDIT:




编辑:


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


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

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



EDIT:




编辑:


In the above example last 2 fields

false, true

specifies the

upsert

and

multi

flags.


在上面的示例中,最后2个字段为

false, true

指定

upsert



multi

标志。



Upsert:

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



Upsert:

如果设置为true,则在没有文档与查询条件匹配时创建新文档。



Multi:

If set to true, updates multiple documents that meet the query criteria.



Multi:

如果设置为true,则更新符合查询条件的多个文档。


If set to false, updates one document.


如果设置为false,则更新一个文档。


This is for Mongo

versions

prior to

2.2

.


这适用于

2.2

之前的Mongo

versions




For latest versions the query is changed a bit


对于最新版本,查询会稍微更改一下

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