After objects have been inserted into a collection, you often need to update them from Java as data changes. The update() method on the DBCollection object enables you to update documents in a collection. The update method is versatile yet fairly easy to implement. The syntax for the update() method follows:
- update(query, update, [upsert], [multi])
The query parameter is a BasicDBObject object that identifies which document(s) you want to change. The request matches the properties and values in the query with the fields and values of the object, and only those that match the query are updated. The update parameter is a BasicDBObject that specifies the changes to make to the documents that match the query. Hour 8, “Manipulating MongoDB Documents in a Collection,” describes the update operators used in this object.
The upsert parameter is a Boolean. When true, if no objects match the query, a new document is created. The multi parameter is also a Boolean; when true, all documents that match the query are updated. When multi is false, only the first document that matches the query is updated.
For example, the following changes the category field value to old for items in the collection, where category currently is new. With upsert set to false, new documents are not created even if no documents have a category of new; with multi set to true, all documents that match are updated:
- BasicDBObject query = new BasicDBObject("category", "New");
- BasicDBObject update = new BasicDBObject("$set",
- new BasicDBObject("category", "Old"));
- update(query, update, false, true);