1

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?

1
  • i want update mongodb by only one update statement. Commented Jan 7, 2014 at 12:22

1 Answer 1

3

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);
Sign up to request clarification or add additional context in comments.

1 Comment

but how can i use this in java?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.