Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add an array to a MongoDB document using Java?

I want to create the following document schema in mongoDB using the java driver

{
  "_id": {
    "$oid": "513e9820c5d0d8b93228d7e8"
  },
  "suitename": "testsuite_name",
  "testname": "testcase_name",
  "milestones": [
    {
      "milestone_id": "359",
      "testplans": [
        {
          "pland_id": "965",
          "runs": [
            6985,
            5896
          ]
        },
        {
          "plan_id": "984",
          "runs": [
            9856,
            3684
          ]
        }
      ]
    }
  ]
}

I have the following code

BasicDBObject testObject = new BasicDBObject();
BasicDBObject milestoneObject = new BasicDBObject();

testObject.put("suitename", testsuite);
testObject.put("testname", testcase);
testObject.put("milestones", new BasicDBObject("milestone_id", "2333"));
locations.insert(testObject);

But this is not generating milestone as an array. How can I add milestone as an array? I currently get this using my code

{
  "_id": {
    "$oid": "513f93dac5d0e2439d34308e"
  },
  "suitename": "test_deployment_disable_client.TestDeploymentDisableClient",
  "testname": "test_deployment_disable_client",
  "milestones": {
    "milestone_id": "2333"
  }
}
like image 319
user2162796 Avatar asked Mar 12 '13 20:03

user2162796


People also ask

How do I append to an array in MongoDB?

If the value is an array, $push appends the whole array as a single element. To add each element of the value separately, use the $each modifier with $push . For an example, see Append a Value to Arrays in Multiple Documents. For a list of modifiers available for $push , see Modifiers.

How do I create an array in MongoDB query?

Case 1 − Create array with MongoDB. If you want to create an array of field UserName and do not want the field _id, use the below query. If you want to create an array with field name _id only, use the below query.

Can we use array in MongoDB?

Unlike relational database models, MongoDB documents can have fields which have values as arrays. The prototypical example in almost all MongoDB documentation is a document having a tags field, whose value is an array of strings, such as ["NoSQL", "Ruby", "MongoDB"] .


1 Answers

Change to something like this:

testObject.put("suitename", testsuite);
testObject.put("testname", testcase);         
List<BasicDBObject> milestones = new ArrayList<>();
milestones.add(new BasicDBObject("milestone_id", "2333"));
testObject.put("milestones", milestones);
locations.insert(testObject);
like image 186
Ori Dar Avatar answered Sep 19 '22 21:09

Ori Dar