简体   繁体   中英

how to insert a document without creating new mongodb connection?

I am trying to develop a java project using mongodb as a database. I have 2 methods (threaded, without thread)

    //myMongoHelper, for connection
    //mydbhelper, threaded insertion

    myMongoHelper m = new myMongoHelper("localhost",27017,"mydb","mycoll");
    int id=100;
    Thread t = new Thread(new mydbhelper(new BasicDBObject()));
    while(id>0){
        t.start();
        t = new Thread(new mydbhelper(new BasicDBObject()));
        id--;
    }
    t.join();
    m.myclose();

and

        int id =100;
        mongoClient = new MongoClient("localhost" , 27017 );
        DBCollection coll = mongoClient.getDB( "mydb" ).getCollection("mycoll");
        while(id>0){
            coll.insert(new BasicDBObject());
            id--;
        }
        mongoClient.close();

$mongod shell shows XX connections now open while execution of a code, and by default it terminates all connections at the end of java execution.

So I want to know,

  1. open connections affects mongodb database and how?
  2. is it possible to terminate a thread after insertion to decrease a count of connections?
  3. Is threading is better for mongodb operations specially for insertion?

Please improve my code.

I'm going to answer all of them together, every new connection takes huge amount of resource in order to initialize, therefore keep them as low as possible.

Instead of creating a new connection for each thread, use a single connection and distribute your query! you can distribute your queries with this way! also you can use bulk insert in order to insert huge amount of docs.

    DBCollection coll = mongoClient.getDB( "mydb" ).getCollection("mycoll");
    ArrayList<BasicDBObject> dbos = new ArrayList<BasicDBObject>();
    while(id>0){
        dbs.add(new BasicDBObject());
        id--;
    }
    coll.insert(dbos);

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