繁体   English   中英

Mongodb 查看数组中的所有项目是否存在并更新否则插入

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

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

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

我目前有:

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

QuestionTags是 db 集合的猫鼬模式。

这似乎不起作用。 我输入了一组新标签,但没有添加它们,也没有增加现有标签。

有没有办法处理这个而不必循环遍历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 集合当前为空,因此不应为空。

我认为您可以在几个查询中完成此操作,而无需循环查询。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM