简体   繁体   中英

How to insert a bulk data seperatly into mongoDB?

I have a json file that contains three datas together. I want to insert all three datas seperatly into the mongodB. Is that possible? if yes then how?

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

Inserting a group of documents from the mongo client shell:

let,

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

Inserting the docs array:

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

This would insert each item in the docs array as separate documents in the collection.

db.collection.find();

would give us, three different documents that were inserted.

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

To do it in Java, you need to load and parse the JSON file using JSON parsing libraries such as Jackson parser, get the docs array and persist it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM