Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rename ($project) a field from an array - MongoDB [duplicate]

I have a document like the following,

{
    "_id" : "59ba903dacea50d0d7d47168",
    "sections" : [ 
        {
            "_id" : "59d9dd7947ce651544c5d4c1",
            "sectionName" : "Section 1"
        }, 
        {
            "_id" : "59d9dd8147ce651544c5d4c2",
            "sectionName" : "Section 2"
        }, 
        {
            "_id" : "59d9dd9747ce651544c5d4c3",
            "sectionName" : "Section 3"
        }
    ]
}

I am using projection to rename the fields _id to id and sectionName to name using the query

db.getCollection('tmp').aggregate([
{$project:{"sections.id":"$sections._id", "sections.name":"$sections.sectionName"}}
])

The desired output is:

{
    "_id": "59ba903dacea50d0d7d47168",
    "sections": [
        {"id": "59d9dd7947ce651544c5d4c1", "name": "Section 1"}, 
        {"id": "59d9dd8147ce651544c5d4c2", "name": "Section 2"}, 
        {"id": "59d9dd9747ce651544c5d4c3", "name": "Section 3"}
    ]
};

But it doesn't seem to work, what am I doing wrong?

Please note that I am not trying to update this document like in this question, I want to project the document in the desired format.

like image 343
Saha K P Ghoshal Avatar asked Mar 09 '18 11:03

Saha K P Ghoshal


1 Answers

If i did understand it well, it should be done via $map operator, like this:

db.getCollection('section').aggregate([
    {
        $project: {
           sections: {
               $map: {
                   "input": "$sections",
                   as: "sec",
                   in: {
                       "my_id": "$$sec._id",
                       "new_section_name": "$$sec.sectionName"
                   }
               }
           }
        }
    }
])

The output is something like bellow:

{
  "waitedMS": NumberLong("0"),
  "result": [
    {
      "_id": "59ba903dacea50d0d7d47168",
      "sections": [
        {
          "my_id": "59d9dd7947ce651544c5d4c1",
          "new_section_name": "Section 1"
        },
        {
          "my_id": "59d9dd8147ce651544c5d4c2",
          "new_section_name": "Section 2"
        },
        {
          "my_id": "59d9dd9747ce651544c5d4c3",
          "new_section_name": "Section 3"
        }
      ]
    }
  ],
  "ok": 1
}
like image 153
felipsmartins Avatar answered Sep 21 '22 08:09

felipsmartins