简体   繁体   English

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

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

I have a mongo collection of tags and when the user enters an array of tags I want to do the following :我有一个 mongo 标签集合,当用户输入一组标签时,我想执行以下操作:

If a tag in the array exists, update the count If a tag in the array does not exist, insert with a count of 0如果数组中存在标签,则更新计数 如果数组中不存在标签,则插入计数为 0

I currently have :我目前有:

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

QuestionTags is the mongoose schema for the db collection. QuestionTags是 db 集合的猫鼬模式。

This does not seem to be working.这似乎不起作用。 I entered an array of new tags and they are not being added, and the existing tags are not being incremented.我输入了一组新标签,但没有添加它们,也没有增加现有标签。

Is there a way to handle this without having to loop through tagArray and make a db call for each item in the array?有没有办法处理这个而不必循环遍历tagArray并对数组中的每个项目进行 db 调用?

UPDATE: Changed my code to this更新:将我的代码更改为此

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

However, newTags is null.但是, newTags为空。 QuestionTags collection is currently empty so it should not be null. QuestionTags 集合当前为空,因此不应为空。

I think you can do this in a few queries, without querying in a loop.我认为您可以在几个查询中完成此操作,而无需循环查询。

1) Update existing tags count : your query works : 1) 更新现有标签计数:您的查询有效:

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

2) Find new tags : 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);
    });

This will give you an array of tags that don't exist in database.这将为您提供数据库中不存在的一系列标签。

3) Insert new tags using result of 2, in the find callback: 3) 在find回调中使用结果 2 插入新标签:

QuestionTags.collection.insertMany(newTagObj);

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

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