Reputation: 397
I have around 20 collection in our mongoDB. One document in one collection has some relationship/association with a document in another collection. We have one common field "executionId" : "some old value" in all the documents across the collections. collection may have one or more documents
I want to iterate through all the collection and if any document matches "executionId" : "some old value" then i want to copy that document and create new document with new value "executionId" : "some new value " in the same collection.
I want to repeat this for all the collection in my mongoDB.
For Example. Below are my collection
collection_one
{
"_id" : ObjectId("5ef615b87127ee8d00229473"),
"executionId" : "some old value",
"application" : "app1",
"status" : "Started"
}
collection_two
{
"_id" : ObjectId("5ef615b87127ee8d00229455"),
"executionId" : "some old value",
"isOrder" : false,
"form" : false,
"officerNumber" : "T643",
"phoneNumber" : "0482",
"createdDate" : ISODate("2020-06-26T15:35:20.889Z"),
"lastModifiedDate" : ISODate("2020-06-26T15:35:25.045Z")
}
collection_three
{
"_id" : ObjectId("5ef615b87127ee8d00229466"),
"executionId" : "some old value",
"application" : "app1",
"country" : "country"
}
After I execute the update query in shell prompt. I want them to look like this.
collection_one
{
"_id" : ObjectId("5ef615b87127ee8d00229473"),
"executionId" : "some new value",
"application" : "app1",
"status" : "Started"
}
collection_two
{
"_id" : ObjectId("5ef615b87127ee8d00229455"),
"executionId" : "some new value",
"isOrder" : false,
"form" : false,
"officerNumber" : "T643",
"phoneNumber" : "0482",
"createdDate" : ISODate("2020-06-26T15:35:20.889Z"),
"lastModifiedDate" : ISODate("2020-06-26T15:35:25.045Z")
}
collection_three
{
"_id" : ObjectId("5ef615b87127ee8d00229466"),
"executionId" : "some new value",
"application" : "app1",
"country" : "country"
}
Upvotes: 0
Views: 225
Reputation: 10662
You can use updateMany for that.
db.collectionName.updateMany(
{ executionId: 'some old value' },
{ $set: { executionId : 'some new value'} }
);
since you want to do this for all the collections in your database, you can try this:
db.getCollectionNames().forEach(collection => {
db[collection].updateMany({ executionId: 'some old value' }, { $set: { executionId : 'some new value'} })
});
Upvotes: 1