Reputation: 2949
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"]
}
Upvotes: 0
Views: 1210
Reputation: 9295
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
Upvotes: 2