我想使用java驱动程序
在mongoDB中创建以下文档模式{
"_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
]
}
]
}
]
}
我有以下代码
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);
但这并不像阵列那样产生里程碑。如何将里程碑添加为数组?我目前使用我的代码
来获取此信息{
"_id": {
"$oid": "513f93dac5d0e2439d34308e"
},
"suitename": "test_deployment_disable_client.TestDeploymentDisableClient",
"testname": "test_deployment_disable_client",
"milestones": {
"milestone_id": "2333"
}
}
答案 0 :(得分:38)
改为这样:
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);
答案 1 :(得分:4)
您可以创建一个接收DBObjects的ArrayList。
List<DBObject> array = new ArrayList<DBObject>();
为数组中的对象添加创建的DBObject,并将其添加到创建的数组对象中。
array.add(/* some object */);
最后,将数组放在主文档对象中。
document.put("milestones", array);
答案 2 :(得分:0)
更好用:
MongoClient client = new MongoClient("localhost",27017);
MongoCollection<Document> collection = client.getDatabase("db").getCollection("collection");
List<Document> docs=new ArrayList<>();
docs.add();
collection.insertMany(docs);
client.close();
答案 3 :(得分:0)
延伸到上一个答案
BasicDBObject testObject = new BasicDBObject();
testObject.put("type", "milestones");
testObject.put("usecase", "milestone_type");
List<BasicDBObject> testplans = new ArrayList<>();
testplans.add(new BasicDBObject("plan_id","3232"));
testplans.add(new BasicDBObject("plan_day","sunday"));
BasicDBObject milestoneObject = new BasicDBObject();
milestoneObject.put("milestone_id", "3232");
milestoneObject.put("plans", testplans);
List<BasicDBObject> milestones = new ArrayList<>();
milestones.add( milestoneObject);
testObject.put("milestones", milestones);
locations.insert(testObject);