How to restore a bson file without affecting the existing data in a collection

Hello,
I need to restore a bson file which contains one or more fields like

{
    type:"xyz"
    isAdmin:"true"
}

Now i need to add these two fields which are present in user.bson file into user collection which already has some data like this

{
    name:"abc"
    age:25
    email:"some@thing.com"
}
{
    name:"efg"
    age:24
    email:"some@thing.com"
}

I want final collection like this

{
    name:"abc"
    age:25
    email:"some@thing.com"
    type:"xyz"
    isAdmin:"true"
},
{
    name:"efg"
    age:24
    email:"some@thing.com"
    type:"xyz"
    isAdmin:"true"
}

Hi,

I don’t think there’s a straightforward method to do what you described.

As I understand it, you have a collection with two documents. Now you want to “restore” a BSON file that contains two additional fields. You wanted each document to be updated with those two fields.

I don’t believe this is possible to do using standard tools like mongorestore or mongoimport, since you’re basically trying to perform an update to each document in the collection. The best way to approach this is to write a script that will:

  1. Take the additional fields you want to be added to all documents
  2. Loop through all documents in the collection, adding the fields into each document, then updating the database.

If you need further help with this, please post more details, e.g. the content of the BSON file with the additional fields, and some example documents from the collection.

Best regards,
Kevin

I am not too sure if that could work but I would try.

  1. I would restore the file in a temporary collection
  2. Investigate to see if https://docs.mongodb.com/manual/reference/operator/aggregation/merge/ or https://docs.mongodb.com/manual/reference/operator/aggregation/mergeObjects/ could be use to obtain the desired result.

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.