Insert Array inside an object in MongoDB

后端 未结 3 683
悲哀的现实
悲哀的现实 2021-02-05 12:11

I am new at MongoDB and I want to insert to mongodb data like this but I couldn\'t figure out how

{
  image = \"cab\"
  tags = [
            [ \"NNP\", 0 ],
             


        
3条回答
  •  醉梦人生
    2021-02-05 13:06

    Basically you use BasicDBObject for key-value mappings and BasicDBList for array objects. For the object in your question, you'd do this:

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

    There's some convenience methods in the api to make this a bit less verbose.

    The mapping works like this:

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

提交回复
热议问题