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" }
EDIT:
如果要向所有集合添加新的_字段,则必须使用空 Select 器,并将multi flag设置为true(last param)以更新所有文档
db.your_collection.update(
{},
{ $set: {"new_field": 1} },
false,
true
)
EDIT:
在上面的示例中,最后两个字段false, true
指定upsert
和multi
标志.
Upsert:如果设置为true,则在没有文档与查询条件匹配时创建新文档.
Multi:如果设置为true,则更新满足查询条件的多个文档.如果设置为false,则更新一个文档.
这是2.2
之前的Mongo versions
.对于最新版本,查询有点变化
db.your_collection.update({},
{$set : {"new_field":1}},
{upsert:false,
multi:true})