How to add an array to a MongoDB document using Java?

前端 未结 4 677
没有蜡笔的小新
没有蜡笔的小新 2020-12-14 09:45

I want to create the following document schema in mongoDB using the java driver

{
  \"_id\": {
    \"$oid\": \"513e9820c5d0d8b93228d7e8\"
  },
  \"suitename\         


        
相关标签:
4条回答
  • 2020-12-14 09:49

    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);
    
    0 讨论(0)
  • 2020-12-14 09:50

    Better use:

    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();
    
    0 讨论(0)
  • 2020-12-14 09:53

    You can create an ArrayList which takes in DBObjects.

    List<DBObject> array = new ArrayList<DBObject>();
    

    Add the created DBObject for the object inside the array and add it to the array object created.

    array.add(/* some object */);
    

    Finally, put the array in the main document object.

    document.put("milestones", array);
    
    0 讨论(0)
  • 2020-12-14 09:54

    Little extending to previous answer

        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);
    
    0 讨论(0)
提交回复
热议问题