java操作mongodb(二)

2014-11-24 01:40:17 · 作者: · 浏览: 1

———————————————————————————————————————————————-

为了方便将完成的内容引用到这里

MongoDB supports atomic, in-place updates as well as more traditional updates for replacing an entire document.

* update()

* save() in the mongo shell

* Modifier Operations

+ $inc

+ $set

+ $unset

+ $push

+ $pushAll

+ $addToSet

+ $pop

+ $pull

+ $pullAll

+ $rename

o The $ positional operator

o Upserts with Modifiers

o Pushing a Unique Value

* Checking the Outcome of an Update Request

* Notes

o Object Padding

o Blocking

* See Also

update()

update() replaces the document matching criteria entirely with objNew. If you only want to modify some fields, you should use the atomic modifiers below.

Here’s the MongoDB shell syntax for update():

db.collection.update( criteria, objNew, upsert, multi )

Arguments:

* 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”; that is, if the record does not exist, insert it

* multi – if all documents matching criteria should be updated

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

save() in the mongo shell

The save() command in the mongo shell provides a shorthand syntax to perform a single object update with upsert:

// x is some JSON style object

db.mycollection.save(x); // updates if exists; inserts if new

save() does an upsert if x has an _id field and an insert if it does not. Thus, normally, you will not need to explicitly request upserts, just use save().

Upsert means “update if present; insert if missing”.

myColl.update( { _id: X }, { _id: X, name: "Joe", age: 20 }, true );

Modifier Operations

Modifier operations are highly-efficient and useful when updating existing values; for instance, they’re great for incrementing a number.

So, while a conventional implementation does work:

var j=myColl.findOne( { name: "Joe" } );

j.n++;

myColl.save(j);

a modifier update has the advantages of avoiding the latency involved in querying and returning the object. The modifier update also features operation atomicity and very little network data transfer.

To perform an atomic update, simply specify any of the special update operators (which always start with a ‘$’ character) with a relevant update document: