mongodb 更新所有数据(Mongodb updates all data)

与更新现有集合字段相同,$set如果指定的字段不存在,将添加新的字段。

看看这个例子:

> 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(最后一个参数)以更新所有文档

db.your_collection.update(

{},

{ $set: {“new_field”: 1} },

false,

true

)

编辑:

在上面的示例中,最后2个字段false, true指定upsert和multi标志。

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

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

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

————————

Like updating an existing set field, $set adds a new field if the specified field does not exist.

Take a look at 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” }

If you want to add new to all collections_ Field, you must use an empty selector and set the multi flag to true (the last parameter) to update all documents

db.your_collection.update(

{},

{ $set: {“new_field”: 1} },

false,

true

)

Edit:

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

Upsert: if set to true, a new document will be created when no document meets the query criteria.

Multiple: if set to true, multiple documents that meet the query criteria will be updated. If set to false, a document is updated.

This is 2.2 before Mongo versions. For the latest version, the query has changed