Michael Skvortsov
Michael Skvortsov

Reputation: 191

MongoDB find document if exist - update else - insert

I have some troubles with mongodb. my code:

            for(var j = 0; j < arrayOfWords.length; ++j) {
              var word = arrayOfWords[j];
              (function(word) {
                if (word.length > 2) {
                  async.waterfall([
                      function(callback) {
                        collection.find({'word': word}).limit(1).toArray(function(err, data) {
                          log.info('find');
                          callback(err, data[0]);
                        })
                      },
                      function(data, callback) {
                        if (typeof data != 'undefined') {
                          log.info('Word found: ' + data);
                          unigramCollection.update({'word': word}, {'$inc' : {'sequence': 1}}, function(err, result) {
                            callback(err, result);
                          });
                        } else {
                          collection.insert({'word': word, 'sequence': 1}, function(err, result) {
                            log.info('Insert done!' + JSON.stringify(result));
                            callback(err, result);
                          })
                        }
                      }
                    ],
                  function(err, result) {
                    if(err) {
                      log.error('error: ' + err);
                    } else {
                      log.info('done!');
                    }
                  });
                }
              })(word);
            }

I don't understand why, but mongoDB at first do all finds, then everything else. console:

2014-05-31T12:27:03.112Z - info: [socket/projects.js] find
2014-05-31T12:27:03.113Z - info: [socket/projects.js] find
2014-05-31T12:27:03.113Z - info: [socket/projects.js] find
2014-05-31T12:27:03.116Z - info: [socket/projects.js] Insert done![{"word":"fhhghg","sequence":1,"_id":"5389ca979a49694e2c7ac7d2"}]
2014-05-31T12:27:03.116Z - info: [socket/projects.js] done!
2014-05-31T12:27:03.117Z - info: [socket/projects.js] Insert done![{"word":"dtrtr","sequence":1,"_id":"5389ca979a49694e2c7ac7d3"}]
2014-05-31T12:27:03.117Z - info: [socket/projects.js] done!
2014-05-31T12:27:03.117Z - info: [socket/projects.js] Insert done![{"word":"jgf","sequence":1,"_id":"5389ca979a49694e2c7ac7d4"}]
2014-05-31T12:27:03.118Z - info: [socket/projects.js] done!

How can I do so that operations were executed in necessary sequence: find, if doc is exist, update this doc, else insert new doc

Upvotes: 0

Views: 3978

Answers (1)

Joachim Isaksson
Joachim Isaksson

Reputation: 181077

Instead of sequencing multiple operations per word, you can do the whole operation using a mongodb upsert;

db.test.update({'word':word}, {'$inc':{'sequence':1}}, {'upsert':true})

That will in a single operation update an existing word, or insert it with sequence 1 if it does not already exist.

Upvotes: 2

Related Questions