批量将多条记录插入mongoDB

时间:2017-01-20 09:46:44

标签: java mongodb insert bulkinsert

如何在mongoDB中以下面的格式插入记录,以及如何从java插入,我想一次插入多条记录。

使用的Jar文件:mongo-java-driver-3.3.0.jar

收藏品的文件:

{
    "_id" : ObjectId("5873sdsd"),
    "macId" : "1", 
    "keys" : [     
        "item1", 
        "item2", 
        "item3", 
        "item4"
    ],         
    "timekey" : "timestamp", 
    "macKey" : "macId"  
}

1 个答案:

答案 0 :(得分:0)

找到以下答案,从java插入记录。

Document documents = new Document();
        documents.put("dummyVal", "MId from step 4"); 
        documents.put("timekey", "timestamp"); 
        documents.put("macKey", "dummyVal"); 
        List<String> litItem = new ArrayList<String>();
        litItem.add("setting1");
        litItem.add("setting2");
        documents.put("keys", litItem); // picked keys from page 4
        documents.put("macKey", "dummyVal"); 
        Document documents1 = new Document();
        documents1.put("dummyVal", "MId from step 4"); 
        documents1.put("timekey", "timestamp");
        documents1.put("macKey", "dummyVal"); 
        List<String> litItem1 = new ArrayList<String>();
        litItem1.add("setting1");
        litItem1.add("setting2");
        documents1.put("keys", litItem); // picked keys from page 4
        documents1.put("macKey", "dummyVal"); 
        docList.add(documents1);
dbCollection.insertMany(docList);

在mongoDB中插入记录的示例:

 db.getCollection('Dummy').insert(
       { dummyVal: "dummyVal" },
{macKey :'dummyVal'},
       { $push: { keys: { $each: [ 'setting1', 'setting1'] } } }
    )