0

i have following structure

{
  "name": "abc",
  "lname": "xyz",
  "data": {
    "1": {
      "info": {
        "test": "test"
      },
      "info1": {
        "test": "test"
      }
    }
  }
}

now i want to add following object in 'data' object

 "2": {
      "info": {
        "test": "test1"
      },
      "info1": {
        "test": "test1"
      }
    }

how to do that in mongodb using mongodb java driver?

1 Answer 1

2

In MongoDB shell you can do it as below :

db.collection.update( {_id:id} , { $set: { "data.2": 
  {
 "info": {"test": "test1" }, "info1": {"test": "test1"}
  } 
}});

In Java driver :

DBObject query = new BasicDBObject("_id", "123"); 
DBObject update = new BasicDBObject(); 
DBObject info = new BasicDBObject("test","test1");
update.put("$set", new BasicDBObject("data.2",
new BasicDBObject("info",info).append("info1",info)); 

collection.update(query, update);
Sign up to request clarification or add additional context in comments.

6 Comments

thank you yathish for response. this query executed successfully but not appending data to existing document object
oops!! instead of "data.2" field i had used "name.2" i have updated the same in the post.
i was already made that change in my mongo query but then also it is not working :( have you tested the same?
yes i have tested the query in the mongo shell.. its working fine.. can u share the results which you are getting after executing this query ?
{ "_id" : ObjectId("55a6090062aefdae06f290b0"), "name" : "abc", "lname" : "xyz", "data" : { "1" : { "info" : { "test" : "test" }, "info1" : { "test" : "test" } } } } i have this record in my test databse and i am running following query db.test1.update( {name:"abc"},{ $set: { "data.2": { "info": {"test": "test1" }, "info1": {"test": "test1"} } }}); this shows nothing in console and my data remains same in database
|

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.