Mongodb查看数组中的所有项是否存在并更新else insert

我有一个mongo标签集合,当用户input一个标签数组时,我想要执行以下操作:

如果数组中存在标签,则更新计数如果数组中的标签不存在,则插入计数为0

我目前有:

QuestionTags.update({'tag': {$in: tagArray}}, {$inc : {'count': +1} }, { upsert: true }); 

QuestionTags是db集合的mongoose模式。

这似乎并没有工作。 我input了一个新的标签数组,他们没有被添加,现有的标签没有增加。

有没有办法处理这个,而不必循环tagArray并为数组中的每个项目调用数据库?

更新:更改我的代码到这个

 QuestionTags.update({'tag': {$in: req.body.tags}}, {$inc : {'count': +1} }, { upsert: true, multi: true }); QuestionTags.find({'tag' :{$nin: req.body.tags}}, function(err, newTags) { console.log("New Tags :" + newTags); var tagArray = []; newTags.forEach(function(tag){ var tagObj = { tag: tag, count: 1 } tagArray.push(tagObj); }); QuestionTags.collection.insert(tagArray); }); 

但是, newTags为空。 QuestionTags集合目前是空的,所以它不应该是null。

我想你可以在几个查询中做到这一点,而不用查询循环。

1)更新现有标签计数:您的查询工作:

 QuestionTags.update({'tag': {$in: tagArray}}, {$inc : {'count': +1} },{multi: true} ); 

2)find新的标签:

 QuestionTags.find({},function(err, tags) { var newTagObj = []; // tags is originally an array of objects // creates an array of strings (just tag name) tags = tags.map(function(tag) { return tag.tag; }); // returns tags that do not exist var newTags = tagArray.filter(function(tag) { // The count = 1 can be done here if (tags.indexOf(tag) < 0) { tag.count = 1; } return tags.indexOf(tag) < 0; }); // creates tag objects with a count of 1 // adds to array // (this can be done in the previous loop) newTags.forEach(function(tag) { var tagObj = { tag: tag, count: 1 } newTagObj.push(tagObj); }); 

这会给你一个在数据库中不存在的标签数组。

3)在findcallback中使用2的结果插入新标签:

 QuestionTags.collection.insertMany(newTagObj);