Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
252 views
in Technique[技术] by (71.8m points)

How to insert multiple documents at once in MongoDB through Java

I am using MongoDB in my application and was needed to insert multiple documents inside a MongoDB collection . The version I am using is of 1.6

I saw an example here

http://docs.mongodb.org/manual/core/create/

in the

Bulk Insert Multiple Documents Section

Where the author was passing an array to do this .

When I tried the same , but why it isn't allowing , and please tell me how can I insert multiple documents at once ??

package com;

import java.util.Date;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.MongoClient;

public class App {

    public static void main(String[] args) {
        try {
            MongoClient mongo = new MongoClient("localhost", 27017);
            DB db = mongo.getDB("at");
            DBCollection collection = db.getCollection("people");

            /*
             * BasicDBObject document = new BasicDBObject();
             * document.put("name", "mkyong"); document.put("age", 30);
             * document.put("createdDate", new Date()); table.insert(document);
             */

            String[] myStringArray = new String[] { "a", "b", "c" };

            collection.insert(myStringArray); // Compilation error at this line saying that "The method insert(DBObject...) in the type DBCollection is not applicable for the arguments (String[])"

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

Please let me know what is the way so that I can insert multiple documents at once through java .

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

DBCollection.insert accepts a parameter of type DBObject, List<DBObject> or an array of DBObjects for inserting multiple documents at once. You are passing in a string array.

You must manually populate documents(DBObjects), insert them to a List<DBObject> or an array of DBObjects and eventually insert them.

DBObject document1 = new BasicDBObject();
document1.put("name", "Kiran");
document1.put("age", 20);

DBObject document2 = new BasicDBObject();
document2.put("name", "John");

List<DBObject> documents = new ArrayList<>();
documents.add(document1);
documents.add(document2);
collection.insert(documents);

The above snippet is essentially the same as the command you would issue in the MongoDB shell:

db.people.insert( [ {name: "Kiran", age: 20}, {name: "John"} ]);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...