update a document in mongoDB using JAVA

Refresh

December 2018

Views

11k time

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

1
BasicDBObject newDocument = new BasicDBObject();
newDocument.append("$set", new BasicDBObject().append("clients", 110));

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

collection.update(searchQuery, newDocument);
hhc
4

Это может быть достигнуто с помощью $ нажимного оператора , который присоединяет значение массива а обновление (...) метод.

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);