1

I would have thought this was straightforward but I think it might give unexpected results. I basically load a few documents into a variable.. then I want to save the whole document back to MongoDB.

Do I have to save each one individually using save https://docs.mongodb.com/manual/reference/method/db.collection.save/

Or can I send them as an array using updatemany https://docs.mongodb.com/manual/reference/method/db.collection.updateMany/

it doesn't seem that clear in the docs how to do that.. if you can.

Thanks for your time.

2
  • What is unclear from the documents? What have you tried so far? Commented Mar 22, 2018 at 8:04
  • There are examples to add new documents in bulk , but not update multiple . Commented Mar 22, 2018 at 8:35

2 Answers 2

3

If you use the Native MongoDB Driver for NodeJs, you can use insertMany if you want to create new documents, I think it will work if you have an array of object (be careful to well name fields) like :

var your_variable = [{a: 1, b: 2, c: 3}, {a: 2, b: 3, c: 1, d: 4}];


db.YourCollection.insertMany(your_variable, function(err, result) {
    // Your treatement
});

If you want to update multiple with multiple value, it's impossible (or after many research I didn't find a good solution), you have to make multiple request.

Sign up to request clarification or add additional context in comments.

3 Comments

Ok, yes I wanted to update multiple not add .thank you .
After, if you want to update multiple documents with the same values, you can using updateMany
how? Can you give an example? Have you tested for sure?
1

To update multiple documents with the same values, you can query like this :

db.YourCollection({/* filter empty to update all document */}, {
    $set: {
        field1: new_value1,
        field2: new_value2
        // etc...
    }
}, function(err, result) {
    // your treatment
});

If you want to update multiple documents but not all, use the method like this :

db.YourCollection({fieldToFilter: value}, {
    $set: {
        field1: new_value1,
        field2: new_value2,
        // etc...
    }
}, function(err) {
    // Your treatment
});

the $set stage is for change the value of the fields, but you can use any operator from : https://docs.mongodb.com/manual/reference/operator/update/

You're not forced to use callback function, you can use Promise too

1 Comment

Thanks.. but not really what I am looking for @Nicolas . I was wanting to load docs , make some changes to them and then save the whole doc ( in bulk ) . I will do them individually.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.