juan garcia
juan garcia

Reputation: 1526

How to update many documents in MongoDB, from a list of documents?

I have the following situation:

Documents to be saved:

[
    {
        character: "Elf",
        mana: 222
    },
    {
        character: "Human",
        mana: 100
    },
    {
        character: "Dwarf",
        mana: 0
    }
]

And I have in my mongodb the following:

[
    {
        character: "Elf",
        mana: 150
    },
    {
        character: "Human",
        mana: 50
    },
    {
        character: "Dwarf",
        mana: 50
    }
]

How is the best way to make an update so the characters get the proper values for their mana?

I cannot assume values to be more than a certain value, and may be I have another 50 more objects of different characters.

If I don't find the character in the database I want to insert the new character, otherwise just update it.

I have being looking in the documentation but looks like updateMany is not what I am looking for, and update one by one looks expensive.

How can I do this properly?

Upvotes: 2

Views: 3065

Answers (1)

nurulnabi
nurulnabi

Reputation: 459

mongodb update can do multiple update but can not accept array to update. So you have to go one by one. If you want to do all parallel then use async.each like below.

async.each(docs, function(doc, next){
    db.collection('characters').update({character:doc.character},{$set:{mana:doc.mana}, $setOnInsert:{character:doc.character}},{upsert:true}, function(err, res){
        next(null, null);
    })
    }, function(err, res){
        // all data have been updated.
    })

Upvotes: 4

Related Questions