0

I have a mongodb collection with around 4-5 million documents. It have a field with name "role": "admin". What I want to do is to convert all the roles to array i.e "role": ["admin"].

I prefer not to use forEach loop. Please help me with this. I am a bit new to mongodb.

old documents

{
  "role": "admin"
}
{
  "role": "mod"
}

to new documents

{
  "role": ["admin"]
}
{
  "role": ["mod"]
}
iamsaksham
  • 2,879
  • 4
  • 26
  • 50

1 Answers1

2

you could do this using aggregation like this (directly from shell) :

db.collection.aggregate([
  {$group: {
     _id: "$_id",
     role: {$push: "$role"}
    }
  },
   {$out: "newCollection"}
])

the $group stage will generate these results:

{ "_id" : ObjectId("5874a728cf097894d781d7f0"), "role" : [ "mod" ] }
{ "_id" : ObjectId("5874a724cf097894d781d7ef"), "role" : [ "admin" ] }

and the $out will write it to a specific collection ( can be a new collection or your existing one).

Be carefull when overwritting an existing collection with $out as you can't undo the operation

felix
  • 9,007
  • 7
  • 41
  • 62
  • Yah your way is the way I want, but i have many additional fields too along with role, it aint working for that. Can u help by modifying a bit? – iamsaksham Jan 10 '17 at 09:49
  • @iamsaksham sure, if you want to keep the other fields, just add them in the $group stage like this : "fieldname": { $first: "$fieldname"} – felix Jan 10 '17 at 09:52