XLordalX
XLordalX

Reputation: 594

MongoDB insert in multiple threads

I am using MongoDB as database. So When I insert a document into the database and very shortly after I do this again, it inserts the document again (I check if the database contains the document before inserting it). The reason it does this, I think, is that I run the update method async which means it takes some time, so at the time it checks if it contains it it's still updating it to the database.

Update method:

public static void updateAndInsert(final String collection, final String where, final String whereValue, final DBObject value)
{
    Utils.runAsync(new Runnable()
    {
        @Override
        public void run()
        {
            if(!contains(collection, where, whereValue))
                insert(collection, value);
            else
                db.getCollection(collection).update(new BasicDBObject(where, whereValue), new BasicDBObject("$set", value));
        }
    });
}

How can I make sure it only inserts it once?

Upvotes: 0

Views: 3124

Answers (1)

Benjamin M
Benjamin M

Reputation: 24567

A question without a question. Wow! :D

You shouln't do it that way, because there are no transactions in MongoDB. But you do have atomic operations on single documents.

Better use an upsert. Within the find part of the upsert, you specify the thing you do within your contains method. (Maybe have a look here: http://techidiocy.com/upsert-mongodb-java-example/ or just google for MongoDB and upsert)

This way you can do contains, insert and update in a single query. That's the way you should do it with MongoDB!

Upvotes: 2

Related Questions