Sn0pY
Sn0pY

Reputation: 347

Select a field of a document in nested array using aggregation

I have the following document:

{
    "options": [
        {
            "cost": 5,
            "value": {
                "en": "Socket, where I can plug in my own cable",
                "fr": "Prise, où je peux brancher mon propre câble"
            }
        },
        {
            "cost" 15,
            "value": {
                "en": "Fixed cable",
                "fr": "Câble fixe"
            }          
        }
    ]
}

And I want to get as value the value of en, something like this:

{
    "options": [
        {
            "cost": 5,
            "value": "Socket, where I can plug in my own cable"
        },
        {
            "cost" 15,
            "value": "Fixed cable"       
        }
    ]
}

I've already tried with $addFields and as field to access with $options.value.en or with nesting. I've tried also with $map but no result.

I don't want to $unwind options and group them after $addFields;

Upvotes: 1

Views: 27

Answers (2)

Ashh
Ashh

Reputation: 46481

You can use below aggregation

db.collection.aggregate([
  { "$addFields": {
    "options": {
      "$map": {
        "input": "$options",
        "in": {
          "cost": "$$this.cost",
          "value": "$$this.value.en"
        }
      }
    }
  }}
])

Upvotes: 1

Mayuri S Kulkarni
Mayuri S Kulkarni

Reputation: 757

Try this:

db.collection.aggregate([
  {
    $unwind: {
      path: "$options"
    }
  },
  {
    $project: {
      "options.cost": 1,
      "options.value": "$options.value.en"
    }
  },
  {
    $group: {
      _id: 0,
      options: {
        $push: "$options"
      }
    }
  }
])

Upvotes: 0

Related Questions