Mongo/Java findAndReplace not working

2k Views Asked by At

I have a Mongo collection like this

email{
"isConfirmed" : true/[or false]
"email" : "xxxxxxxxxxx"
}

When I am trying to update the isConfirmed field to true or false, depending on the email which apparently is unique, it takes ages.

The programming language I am using is Java

Here's my code.

List<String> clientEmails = new ArrayList<String>();

Mongo mongoConnection = new Mongo();

DB mongoDatabase = mongoConnection.getDB(DB_NAME);

DBCollection mongoCollection = mongoDatabase.getCollection(COLLECTION_NAME);

int size = clientEmails.size();

for(int i=0;
i
<
size; i++)

{

    BasicDBObject query = new BasicDBObject();

    System.out.println(clientEmails.get(i).toString());

    query.put("email.email", clientEmails.get(i).toString());

    BasicDBObject Update = new BasicDBObject("$set", new   BasicDBObject("email.isConfirmed", false));

    mongoCollection.update(query, Update); 

This one takes ages to run through the collection which consists of around 3500 entries]

  //mongoCollection.findAndModify(query, Update);

Even findAndModify doesn't work at all, I am not sure if I am missing something here

However, I have tried with the DBcursor, it works but it takes around 3 minutes to run.

//             DBCursor cursor = mongoCollection.find(query);
//

//             while(cursor.hasNext()){

//                 BasicDBObject Update = new BasicDBObject("$set", new BasicDBObject("email.isConfirmed", true));

//                 mongoCollection.update(cursor.next(), Update);
//             }

This method takes around 3 minutes. Can someone suggest me of a workaround or something?

2

There are 2 best solutions below

3
On

Do you have an index on email.email? If not the query has to do a complete collection scan to find the correct document every time you call update.

You also might want to run mongostat for a while to see what else is going on that could be causing the slowdown. mongostat -h will explain what all the fields mean.

0
On

If you were using IDE(like Eclipse) download mongo java driver source as well. Set up breakpoint at

mongoCollection.findAndModify(query, Update); Step into the java driver, actually you could find excatlly cmd string send to mongo. also actual result from mongo db which should give you more information. Also you can copy/paste cmd string and put into mongo shell, and see what happens next.

I got a issue with findAndModify method, by troubleshooting as I said, found I used wrong 'COLLECTION_NAME' in my code.

I'm using mongo v1.8 and java driver v2.5.3, this method works for me.