Home > database >  MongoDB - How to unwrap nested json
MongoDB - How to unwrap nested json

Time:11-12

My documents in collection,

[
    {
        "_id": {
            "uuid": "aaa",
            "sectionId": "1"
        },
        "name": "tmp"
    },
    {
        "_id": {
            "uuid": "bbb",
            "sectionId": "2"
        },
        "name": "tmp"
    },
    {
        "_id": {
            "uuid": "ccc",
            "sectionId": "3"
        },
        "name": "tmp"
    }
]

Need something like this in output:

_id.uuid -> slot_id

_id.sectionId -> id

name -> slot_name

[
    {
        "slot_id": "aaa",
        "id": "1",
        "slot_name": "tmp"
    },
    {
        "slot_id": "bbb",
        "id": "2",
        "slot_name": "tmp"
    },
    {
        "slot_id": "ccc",
        "id": "3",
        "slot_name": "tmp"
    }
]

I have an ugly looking working in Java, but I am quite sure mongodb has a nice way of doing it..

Please help!! Thanks in advance.

CodePudding user response:

Using find you can use projection stage like this:

db.collection.find({},
{
  "_id": 0,
  "slot_id": "$_id.uuid",
  "id": "$_id.sectionId",
  "slot_name": "$name"
})

Example here

Using aggregate simply use $project like this:

db.collection.aggregate([
  {
    "$project": {
      "_id": 0,
      "slot_id": "$_id.uuid",
      "id": "$_id.sectionId",
      "slot_name": "$name"
    }
  }
])

Example here

  • Related