I have a collection that have many documents with too many fields but I want to gather many of these fields inside new field called Data, here is an example
{
"_id" : ObjectId("***********"),
"name" : "1234567890",
"mobile" : "Test",
.
.
.
.
.
etc
}
I want to use updateMany to make all the documents in the collection looks like this
{
"_id" : ObjectId("***********"),
"name" : "1234567890",
"mobile" : "Test",
"Data":{
.
.
.
.
.
etc
}
}
Option 1(few nested fields): You can do it following way:
db.collection.update({},
[
{
$project: {
data: {
name: "$name",
mobile: "$mobile"
}
}
}
],
{
multi: true
})
Option 2: (If the fields that need to be nested are too many):
db.collection.update({},
[
{
$project: {
data: "$$ROOT",
name: 1,
mobile: 1
}
},
{
$unset: [
"data.name",
"data.mobile"
]
}
],
{
multi: true
})