如果存在MongoDB查找文档 - 更新else - 插入

时间:2014-05-31 12:47:52

标签: javascript node.js mongodb asynchronous

我和mongodb有些麻烦。 我的代码:

            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);
            }

我不明白为什么,但mongoDB起初都会发现,然后是其他一切。 控制台:

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!

如何执行操作以必要的顺序执行:如果存在doc,则查找更新此文档,否则插入新文档

1 个答案:

答案 0 :(得分:2)

您可以使用mongodb upsert进行整个操作,而不是按字排序多个操作;

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

这将在单个操作中更新现有单词,或者如果它尚不存在则将其插入序列1。