在 MongoDB 中的对象内插入数组

2022-09-03 12:26:37

我是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 }
             ]

},

谢谢


答案 1

基本上,您将 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);

答案 2

你的意思是这样的吗?

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