Mongodb查看数组中是否所有项都存在,并更新else插入

Mongodb see if all items in array exist and update else insert

本文关键字:存在 更新 插入 else 数组 是否 Mongodb      更新时间:2023-09-26

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

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

我目前有:

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

QuestionTags是数据库集合的mongoose模式。

这似乎不起作用。我输入了一个新标签的数组,它们不会被添加,现有的标签也不会增加。

有没有一种方法可以在不必循环通过tagArray并对数组中的每个项进行db调用的情况下处理此问题?

更新:将我的代码更改为此

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) 查找新标签:

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) 在find回调中使用2的结果插入新标签:

QuestionTags.collection.insertMany(newTagObj);