Home > Back-end >  MongoDB- How to $project items from an object?
MongoDB- How to $project items from an object?

Time:03-05

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.

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 ?

CodePudding user response:

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}}])
  • Related