Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

MongoDB- How to $project items from an object?

Playground https://mongoplayground.net/p/tIMLOtWTnno

DATA:

[

  {
    "_id": "1",
    "data": {                     // How to remove this "data" Field
      "colour": "Blue",
      "size": "12",
    }
  },
  {
    "_id": "2",
    "data": {                     // How to remove this "data" Field
      "colour": "Silver",
      "size": "20",
    }
  }

]

I want to remove the data field.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Expected Output:

[
  {
    "_id": "1",
    "colour": "Blue",
    "size": "12",
    
  },
  {
    "_id": "2",
    "colour": "Silver",
    "size": "20",
    
  }
]

Tried it like this:

db.collection.aggregate({
  $project: {
    _id: 1,
    data: {
      $objectToArray: "$data"
    }
  },
  
},
{
  $unwind: "$data"
},
{
  $project: {
    "$data.k": "$data.v"
  }
})

How to do this ?

>Solution :

Query1

  • set to add the fields in the root and remove the data

*you could use also project

Test code here

aggregate(
[{"$set":
  {"colour":"$data.colour",
   "size":"$data.size",
   "data":"$$REMOVE"}}])

Query2

  • more general solution without the need to type each field in project
  • merge the data embeded object with the root, and make it new root
  • remove the data field

Test code here

aggregate(
[{"$replaceRoot":{"newRoot":{"$mergeObjects":["$data", "$$ROOT"]}}},
 {"$project":{"data":0}}])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading