1

I am trying to migrate data in mongodb from old schema to new schema in mongodb. where slug_url is added which is exact copy of value of key 'name'. how can i acheive this using mongoshell ?

Previous Data :

{
name:'test',
}

Want

{
name:'test',
slug_url:'test'
}
Soumen Mukherjee
  • 2,953
  • 3
  • 22
  • 34
manoj
  • 5,235
  • 7
  • 24
  • 45
  • This is a long standing question with long standing answers. [The MongoDB 4.2 solution](https://docs.mongodb.com/manual/reference/method/db.collection.updateMany/#update-with-an-aggregation-pipeline) ( if you have it ) would be `.updateMany({ }, [{ "$set": { "slug_url": "$name" } }])`. Older solutions are also documented on the existing answers. – Neil Lunn Sep 22 '19 at 06:12

1 Answers1

1

It can be done using forEach -

db.<collectionName>.find().forEach(function(result) 
{ 
db.<collectionName>.update({"_id" : result._id}, {$set : {"slug_url" : result.name}}); 
})
Ajay Srivastava
  • 1,151
  • 11
  • 15
  • Just a side note, using for loop instead of the forEach will be much better here, since forEach doesn't await. Otherwise it's all good. – Vikrant Bhat Sep 16 '21 at 07:15