我是MongoDB的新手,我想插入像这样的mongodb数据,但我无法弄清楚如何
{
image = "cab"
tags = [
[ "NNP", 0 ],
[ "NN", 1 ]
]
},
{
image = "castle"
tags = [
[ "NNP", 2 ],
[ "NN", 1 ],
]
}
我的代码是
BasicDBObject obj = new BasicDBObject();
obj.put("images", ....);
for(Tag tag:tags){
BasicDBObject tagsObj = new BasicDBObject();
tagsObj.put("NNP",tag.getNNP());
tagsObj.put("NN",tag.getNN());
obj.put("tags",tagsObj);
}
更新: 使用此代码
Mongo m = new Mongo();
DB db = m.getDB("test");
DBCollection coll = db.getCollection("tags");
for(Tag tag:tags){
BasicDBList dbl = new BasicDBList();
dbl.add(new BasicDBObject("NNP",tag.getNNP()));
dbl.add(new BasicDBObject("NN", tag.getNNP()));
BasicDBObject outer=new BasicDBObject("images", currentImageName).append("tags", dbl);
coll.insert(outer);
}
我单独存储每个图像,因为标签对于同一图像可能是这样的
{
image = "cab",
tags = [
{ "NNP", 0 },
{ "NN", 1 }
],
[ {"NNP", 4 },
{ "NN", 5 }
],
[
{"NNP", 0 },
{ "NN", 4 }
]
},
由于
答案 0 :(得分:25)
基本上,您将BasicDBObject用于键值映射,将BasicDBList用于数组对象。对于你问题中的对象,你可以这样做:
BasicDBList dbl = new BasicDBList();
dbl.add(new BasicDBObject("NNP",0));
dbl.add(new BasicDBObject("NN", 1));
BasicDBOBject outer=new BasicDBObject("image", "cab").append("tags", dbl);
api中有一些方便的方法可以使它更简洁。
映射的工作原理如下:
for: {"A":1} use: new BasicDBObject("A",1)
for: {"A":1, "B":2} use: new BasicDBObject("A",1).append("B",2)
for: {"A":{"B":2}} use: new BasicDBObject("A",new BasicDBObject("B",2))
for: {"A":["B","C"]} use:
BasicDBList dbl = new BasicDBList();
dbl.add("B");
dbl.add("C");
-> new BasicDBObject("A",dbl);
答案 1 :(得分:3)
你的意思是这样吗?
BasicDBObject obj = new BasicDBObject();
obj.put("image", ....);
for(Tag tag:tags){
BasicDBObject tagsObj = new BasicDBObject();
tagsObj.put("NNP",tag.getNNP());
tagsObj.put("NN",tag.getNN());
obj.put("tags",tagsObj);
}
答案 2 :(得分:0)
以下是我在使用mongo3.x时的使用方法:
假设您希望结果如下:{"data": [{"key":"v1"}, {"key":"v1"}, {"key":"v1"}] }
[step1]:使用Java Map创建映射到数组内部元素的json对象;也就是说,[]
中的{} [step1 Ans]:Map m1,m2,m3 = new HashMap(); m1.put("key", "v1"); m2.put("key", "v1"); m3.put("key", "v1");
[step2]:使用Java List将所有Java Map添加到一个元素中。
[step2 Ans]:List list = new ArrayList(); list.add(m1); list.add(m2); list.add(m3);
[step3]:将Java列表添加到mongo
[step3 Ans]:Document dc = new Document("key", list);