向 MongoDB 集合中的每个文档添加新字段
如何向现有集合中的每个文档添加新字段?
How can I add a new field to every document in an existent collection?
我知道如何更新现有文档的字段,但不知道如何向集合中的每个文档添加新字段.如何在 mongo
shell 中执行此操作?
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?
与更新现有集合字段相同,$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
指定了 upsert
和 multi
标志.
In the above example last 2 fields false, true
specifies the upsert
and multi
flags.
Upsert: 如果设置为 true,则在没有文档与查询条件匹配时创建一个新文档.
Upsert: If set to true, creates a new document when no document matches the query criteria.
Multi: 如果设置为 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})