如何将批量数据分别插入到mongoDB中?

How to insert a bulk data seperatly into mongoDB?

我有一个 json 文件,其中包含三个数据。我想将所有三个数据分别插入 mongodB。那可能吗?如果是那么怎么办?

{
    "docs": [
        {
            "_id": "First",           
            "count": 4,
            "name": "Fish",
        },
        {
            "_id": "Second",           
            "count": 6,
            "name": "Meat"
        },
        {
            "_id": "Third",            
            "count": 8,
            "name": "Vegetables"
        }
    ]
}

正在从 mongo 客户端插入一组文档 shell:

让,

var input = {
    "docs": [
        {
            "_id": "First",           
            "count": 4,
            "name": "Fish",
        },
        {
            "_id": "Second",           
            "count": 6,
            "name": "Meat"
        },
        {
            "_id": "Third",            
            "count": 8,
            "name": "Vegetables"
        }
    ]
}

正在插入 docs 数组:

db.collection.insert(input["docs"]);

这会将 docs 数组中的每个项目作为集合中的单独文档插入。

db.collection.find();

会给我们插入三个不同的文档。

{ "_id" : "First", "count" : 4, "name" : "Fish" }
{ "_id" : "Second", "count" : 6, "name" : "Meat" }
{ "_id" : "Third", "count" : 8, "name" : "Vegetables" }

要在Java中完成,需要使用JSON解析库(如Jackson解析器)加载并解析JSON文件,获取docs数组并坚持下去。