0

I have the following array of objects...

[
    {
        _id: 'dfjkldsjfkldjas',
        name: 'will'
    },
    {
        _id: 'fdsfdakjdhfaskh',
        name: 'bob'
    },
    {
        _id: 'fdsfdasfdfewrfq',
        name: 'tom'
    }
]

Is there a way to search a mongodb collection for documents that match these _id's and then $set the name in the document all in one query? Maybe using updateMany?

2 Answers 2

1

Try this for updating bulk data

 const data = [
        {
            _id: 'dfjkldsjfkldjas',
            name: 'will'
        },
        {
            _id: 'fdsfdakjdhfaskh',
            name: 'bob'
        },
        {
            _id: 'fdsfdasfdfewrfq',
            name: 'tom'
        }
    ]
    const bulkData = data.map(item => (
        {
            updateOne: {
                filter: { _id: item._id },
                update: { $set: { name: item.name } },
                upsert: true 
            }
        })
    );
await db1.bulkWrite(bulkData, { ordered: false, upsert: true });
Sign up to request clarification or add additional context in comments.

Comments

0

You can use a bulkWrite to achieve this. First map your array and transform the data like so:

const data = [
    {
        _id: 'dfjkldsjfkldjas',
        name: 'will'
    },
    {
        _id: 'fdsfdakjdhfaskh',
        name: 'bob'
    },
    {
        _id: 'fdsfdasfdfewrfq',
        name: 'tom'
    }
]

const bulkData = data.map(item => (
  {
     updateOne: {
        filter: { _id: item._id },
        update: { $set: { name: item.name }}
     }
  })
);

Then you use the method bulkWrite to save the multiple data.

db.yourCollection.bulkWrite(bulkData);

You also don't have to use the same DB operation for every entry, you can use different ones on the same bulk like deleteOne, replaceOne, insertOne, etc.

You can check more here: https://docs.mongodb.com/manual/reference/method/db.collection.bulkWrite/

Comments

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.