1

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
}
    }
Sh.
  • 11
  • 2

1 Answers1

0

Option 1(few nested fields): You can do it following way:

db.collection.update({},
[
  {
   $project: {
     data: {
      name: "$name",
      mobile: "$mobile"
      }
    }
 }
],
{
  multi: true
})

playground1

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
})

playground2

R2D2
  • 9,410
  • 2
  • 12
  • 28
  • 1
    but the number of fields I want to gather is huge , I can not list them all, I need a way that I do not have to list manually – Sh. Mar 05 '22 at 11:11
  • Added option 2 to my answer where the fields that need to be nested are too much and different number , but the fields in the document root are the name & mobile only... – R2D2 Mar 05 '22 at 13:48
  • 1
    Thank you @R2D2, i accepted your answer – Sh. Mar 07 '22 at 17:21