1

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;

2 Answers 2

1

You can use below aggregation

db.collection.aggregate([
  { "$addFields": {
    "options": {
      "$map": {
        "input": "$options",
        "in": {
          "cost": "$$this.cost",
          "value": "$$this.value.en"
        }
      }
    }
  }}
])
Sign up to request clarification or add additional context in comments.

1 Comment

Works like a charm, thank you, I've updated a bit, "in": {$mergeObjects: ['$$this', {"value": "$$this.value.en"}]}
0

Try this:

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

1 Comment

I specify in the question: I don't want to use $unwind and $group.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.