node.js - How to batch update a set of data in mongo and perform an insertion operation when the data in the array does not exist?
淡淡烟草味
淡淡烟草味 2017-05-24 11:35:41
0
2
1009

For example, I have a tag table in mongo, and the data model is as follows

    {
        name: String,
        hot: {
            type: Number,
            default: 0
        },
        create_at: {
            type: Date,
            default: Date.now
        }
    }

Now I have an array of tag names, such as ['mongoDB','node.js','mysql'],
I want to update the popularity in batches, and if it is found that there is no such tag, insert it, implement something like

mongo.tags.update({
    name:{
        $in:['mongoDB','node.js','mysql']
        }
},{
    $inc:{
        hot:1
    }
},{
    upsert: true,
    multi:true
})

Such an operation, but now when I execute this command, an empty data is added

The way I implement it now is to do a query first, Updates that can be queried can be queried, and insertion operations cannot be performed. However, such an operation requires traversing the tag array multiple times from the code, and the performance is not good. I would like to ask if any experts have a better solution.

淡淡烟草味
淡淡烟草味

reply all(2)
左手右手慢动作

1. Your update operation statement is OK;

2. What you said about adding an empty data is because no document that meets the conditions was found and upsert was set to true, so a document containing feild hot was inserted.

You might as well check the document status of your collection and try again. No problem was found in your update operation.

For reference.

Love MongoDB! Have fun!


The 2017 MongoDB Chinese Community Beijing User Group Conference is coming soon! Scan the QR code to register!

某草草

It should be possible to use upsert in mongodb
upsert({},{},true) true means write if there is no, and update if there is;
You can refer to the official support forum:
http://forum.foxera.com/ mongo...

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template