سؤال

MongoDb 2.4.7

mongo-java-driver-2.11.2.jar

Windows 7

So im trying to load test mongodb by inserting a batch of inserts to judge how much throughput it can handle. if do the insert one at a time it works:

...

MongoClient conn = new MongoClient("localhost", 27017);
DB db = conn.getDB( "myDb" );

BasicDBObject jobRecord = new BasicDBObject(...);

DBCollection coll = db.getCollection("myTable");

BasicDBObject finalJobRecord;

for(int i=0;i<100;i++)
{
    finalJobRecord = jobRecord;
    finalJobRecord = finalJobRecord.append("recnum",String.valueOf(i));
    coll.insert(finalJobRecord); 
    finalJobRecord.removeField("_id");// wont work without because of duplicate key errors
}
conn.close();

Now if i change that to batch it dont work (Duplicate key Exception fires):

...

MongoClient conn = new MongoClient("localhost", 27017);
DB db = conn.getDB( "myDb" );

BasicDBObject jobRecord = new BasicDBObject(...);

DBCollection coll = db.getCollection("myTable");

BasicDBObject finalJobRecord;

List<DBObject> basicDBObjects = new LinkedList<>();

for(int i=0;i<100;i++)
{
    finalJobRecord = jobRecord;
    finalJobRecord = finalJobRecord.append("recnum",String.valueOf(i));
    basicDBObjects.add(finalJobRecord);
}
coll.insert(basicDBObjects);
conn.close();
هل كانت مفيدة؟

المحلول

You will end up with the list of identical objects (all list entries would reference the same object) with {"recnum" : 99}, seems that it's not what you're intented to do. You need to create new BasicDBObject on each for-loop iteration, otherwise you will modify the same jobRecord on each iteration.

The same applies to one-by-one approach: you're observing different "recnum" fields because the object is already inserted into Mongo, before it's modified.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top