简体   繁体   中英

MongoDB Update Multiple Documents based on ObjectID (_id)

I'm using the Java driver with MongoDB. I have a List of document id's in a collection. I want to update a single field in every document that has an "_id" equal to one of the document id's in my List. In the below example, I tried something like this:

List<ObjectID> list = new ArrayList<ObjectID>();
list.append(new ObjectId("123"));
list.append(new ObjectId("456"));
list.append(new ObjectId("789"));

column.updateMulti(new BasicDBObject("_id", list),new BasicDBObject("$set",new BasicDBObject("field",59)));

My intentions are to update the documents with _id=123, _id=456 and _id=789, setting their "field" attribute to 59.

Am I going about this the right way?

I believe you need to make a couple changes:

BasicDBList list = new BasicDBList();
list.add( new ObjectId("123") );
// Add the rest...

DBObject inStatement = new BasicDBObject( "$in", list );
column.updateMulti( new BasicDBObject( "_id", inStatement ), new BasicDBObject( "$set", new BasicDBObject( "field", 59 ) );

Otherwise, with your current query, you're doing an equality comparison of the _id property against a list of _ids - not actually using the $in operator.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM