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"
}
}
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.
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.
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"] .
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With