简体   繁体   中英

java mongodb update specific with array

I have the following doc stored in MongoDB:

{ 
  "id" : "5101",
  "contractId" : "001",
  "dueId" : [{"id":"001"},{"id":"002"}],
  "overdueAmount" : "",
  "amount" : "",
  "customerContact" : "Humus"
}

and I want to update to follow data:

{ 
  "id" : "5101",
  "contractId" : "001",
  "dueId" : [{"id":"001"},{"id":"002"},{"id":"003"}],
  "overdueAmount" : "200",
  "amount" : "100",
  "customerContact" : "Bim"
}

you can see dueId is updated(insert a element) and amount , overdueAmount , customerContact are also updated.

How can I use mongodb use update?

By using $push operator you can add new items into the array and $set operator you can update other fields.

The query should be like :

db.collection.update({"id":"5101"},{$push:{"dueId" : {"id" : "003"}}, $set : {"overdueAmount":"200", "amount" : "100", "customerContact" : "Bim"}})

By using Java driver :

DBCollection coll = ...

DBObject query = new BasicDBObject("id", "5101");

DBObject pushObj = new BasicDBObject("dueId", new BasicDBObject("id", "003"));

DBObject setObj = new BasicDBObject();
setObj.put("overdueAmount", "200");
setObj.put("amount", "100");
setObj.put("customerContact", "Bim");

DBObject updateObj = new BasicDBObject();
updateObj.put("$push", pushObj);
updateObj.put("$set", setObj);

coll.update(query, updateObj);

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