2

I'm just starting to learn mongoDB using JAVA. I have the the following document in mongo

{
"_id": {
    "$oid": "513fa587c5d0cf174eb9b1f8"
},
"suitename": "test_suite_name",
"testname": "test_name]",
"milestones": [
    {
        "milestone_id": 45
    }
]
}

I have a compound key on suitename, testname, and milestone_id. I have to process a file which has these three fields. I create a simple DBObject query and check if count != 0

BasicDBObject query = new BasicDBObject();
query.put("suitename", testsuite);
query.put("testname", testcase);
query.put("milestones.milestone_id", SampleProgram.milestone_id);

If count == 0 --> add document in mongo -> this seems to work fine

What I am trying to figure out is: If I have a new value of milestone_id in my file, I just need to add a milestone to some existing document's milestone array. Existing document is determined based on suitename AND testname.

So if milestone_id = 10, the document should look like

{
"_id": {
    "$oid": "513fa587c5d0cf174eb9b1f8"
},
"suitename": "test_suite_name",
"testname": "test_name]",
"milestones": [
    {
        "milestone_id": 45
    },
    {
        "milestone_id": 10
    }

]
}

How can I accomplish this?

Thanks

2 Answers 2

4

This can be accomplished with the $push operator which appends values to an array and the update(…) method.

BasicDBObject query = new BasicDBObject();
query.put("suitename", testsuite);
query.put("testname", testcase);

BasicDBObject push = new BasicDBObject();
push.put("$push",
  new BasicDBObject("milestones",
    new BasicDBObject("milestone_id", SampleProgram.milestone_id)));

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

3 Comments

Works great. Can you tell me where you got the API reference for put?
@user2162796 I have the feeling too that the MongoDB page is structured somehow weirdly, but you can find the API docs for the various versions for Java here. All the info can be found in the appropriate "language centers"... (I can't exactly express why I'm frustrated by the structure of the page, but I fell like struggling each time I need something...)
@user2162796: Since I knew the right term I just googled for it.
1
BasicDBObject newDocument = new BasicDBObject();
newDocument.append("$set", new BasicDBObject().append("clients", 110));

BasicDBObject searchQuery = new BasicDBObject().append("hosting", "hostB");

collection.update(searchQuery, newDocument);

1 Comment

You should explain the answer as well

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.