> db.test_2.find({id:1}); { "_id" : ObjectId("50a0d46ceb825d827b0c3f9b"), "id" : 1, "name" : "francs" } { "_id" : ObjectId("50a12e34f73f2e4aa1ff71bc"), "id" : 1, "name" : "francs" } |
--1.2 更新 id=1 的 documents 的 name 字段为 'name_2'
> db.test_2.update({id:1},{$set:{name:'name_2'}}); |
> db.test_2.find({id:1}); { "_id" : ObjectId("50a0d46ceb825d827b0c3f9b"), "id" : 1, "name" : "name_2" } { "_id" : ObjectId("50a12e34f73f2e4aa1ff71bc"), "id" : 1, "name" : "francs" } |
二. 更新多条记录
--2.1 查询 id=2 的 documents
> db.test_2.find({id:2}); { "_id" : ObjectId("50a0d46ceb825d827b0c3f9c"), "id" : 2, "name" : "fpZhou" } { "_id" : ObjectId("50a12e7cf73f2e4aa1ff71bd"), "id" : 2, "name" : "fpZhou" } { "_id" : ObjectId("50a12f47f73f2e4aa1ff71be"), "id" : 2, "name" : "fpZhou" } |
> db.test_2.update({id:2},{$set:{name:'name_3'}},{multi:true}); |
> ;db.test_2.find({id:2}); { "_id" : ObjectId("50a0d46ceb825d827b0c3f9c"), "id" : 2, "name" : "name_3" } { "_id" : ObjectId("50a12e7cf73f2e4aa1ff71bd"), "id" : 2, "name" : "name_3" } { "_id" : ObjectId("50a12f47f73f2e4aa1ff71be"), "id" : 2, "name" : "name_3" } |
备注:默认情况下 update() 仅更新第一条匹配的记录,如果想更新多条,需要设置
multi 参数为
true。
> db.test_2.find({id:6}); |
备注:id=6 的记录不存在。
--3.2 不加 upsert 参数的更新
> db.test_2.update({id:6},{$set:{name:'name_6'}}); > db.test_2.find({id:6}); > |
备注:这时更新后,没有新增 id=6 的记录。
--3.3 带 upsert 参数的更新
>
db.test_2.update({id:6},{$set:{name:'name_6'}},{upsert:true}); > db.test_2.find({id:6}); { "_id" : ObjectId("50a1328f7543857379c2bb38"), "id" : 6, "name" : "name_6" } > |
备注:如果被更新的 document 不存在,可以通过指定 upsert 参数确定是否要插入
一条新记录,如果为 truce 则插入,否则,不插入。
criteria - query which selects the record to
update;
objNew - updated object or $ operators
(e.g., $inc) which manipulate the
object
upsert - if this should be an "upsert"
operation; that is, if the record(s) do
not
exist, insert one. Upsert only inserts a single document.
multi - indicates if all
documents matching criteria should be updated rather
than
just one. Can be useful with the $ operators below.
If you are coming from SQL, be aware
that by default, update() only modifies
the first matched object. If you want to modify
all matched objects, you need
to use the multi flag.