1

I have the following java-program, that should insert 2 records in the table testcoll:

package mongodbTest;

import java.net.UnknownHostException;

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

public class HelloMongoDB {

    public static void main(String[] args) {

        Mongo mongo = null;
        DB db=null;
        DBCollection table=null;

        // Connection to the MongoDB-Server
        try {
            mongo = new Mongo("localhost", 27017);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }

        //insert data
        db = mongo.getDB("testdb");
        table = db.getCollection("testcoll");

        //create document and insert
        BasicDBObject document = new BasicDBObject();
        document.put("name", "Andre");
        document.put("age", 34);

        BasicDBObject document2 = new BasicDBObject();
        document2.put("name", "Beatrix");
        document2.put("age", 19);

        table.insert(document);
        table.insert(document2);

    }
}

Like you can see, it should insert 2 records into the collection testcoll, but it only insert the first one.

> db.testcoll.find()
{ "_id" : ObjectId("54369b986d4b35dd1125e7ea"), "name" : "Andre", "age" : 34 }

Any suggestions?

Greetings, Andre

Andre
  • 1,249
  • 1
  • 15
  • 38
  • If i am running exactly the same code, i am able to retrieve both the documents, are you sure you checked correctly.? – Jhanvi Oct 10 '14 at 07:45
  • have a better look at the way you handle the exceptions. If the exception happens, means you failed to connect, you should not continue to try insert documents. – SQL.injection Oct 12 '14 at 07:40

2 Answers2

0

There is no problem with your code. You can add List of objects like this!!!

Community
  • 1
  • 1
Vijay
  • 1
0

Try replacing "new Mongo" with "new MongoClient", which will default to acknowledged writes and therefore throw exceptions if any of the inserts fail.

See the Javadoc for the two classes, which explains the difference.

http://api.mongodb.org/java/current/com/mongodb/Mongo.html http://api.mongodb.org/java/currrent/com/mongodb/MongoClient.html

You can also insert a list of documents using the overloaded insert method:

http://api.mongodb.org/java/current/com/mongodb/DBCollection.html#insert(java.util.List)

jyemin
  • 3,743
  • 23
  • 16