1

Im trying to batch insert 100 of the doc Objects. Am I using the insert statement incorrectly?

Mongo mongoClient = new Mongo( "localhost" , 27017 );
    DB db = mongoClient.getDB( "user" );    
    DBCollection coll = db.getCollection("test");
    BasicDBObject doc = new BasicDBObject("userName","James").append("random1", "feeof").append("random2", "ofeijfefe");

    List<DBObject> postsList = new ArrayList<DBObject>(); 
    for ( int i = 0; i != 100; i++)
    {

        postsList.add(doc);
    }

    coll.insert(postsList);

It doesn't insert anything ,when i inspect the last line it shows the value as N/A.

7
  • How do you check it hasn't inserted anything? Commented Feb 27, 2013 at 2:00
  • db.test.count() in console Commented Feb 27, 2013 at 2:02
  • You might not be looking in the right DB. Did you execute usedb user before looking at the count? Commented Feb 27, 2013 at 2:05
  • edit* Yes checked that and it isn't because of that. Commented Feb 27, 2013 at 2:51
  • I'm sorry it should be use user. Commented Feb 27, 2013 at 4:29

1 Answer 1

3

I think this is what is happening here.

The object doc is being added to postsList 100 times. Remember it is the same object at all those 100 places in the list.

Mongo creates an _id attribute for a document if it isn't already there. Once it puts this attribute in the first BasicDBObject in the list every other entry in the list gets modified with the same _id.

I believe because this _id attribute is same for all the entries in the list (which is like a primary key), only the first entry gets inserted.

You can solve this by adding a copy of the doc to the list. Try this:

for (int i = 0; i < 100; i++) {
    postsList.add((BasicDBObject) doc.copy());
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.