mongodbstudio3t

How can I gather all fields with their values except five of them and put them inside new field in the same collection with mongoDB


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

Solution

  • 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