0

I have a schema like this

{
    _id:ObjectId(),
    ...,
    translations:[{
        value: "English",
        code:"en"
    },{
        value: "German",
        code:"de"
    }]
}

All object have a translation with code 'en' and 'de', How can I get all objects(value,id) with code 'en'? A The result should look like similar to this:

[{
    _id:ObjectId(),
    value:"English"
},....
...]
styvane
  • 59,869
  • 19
  • 150
  • 156
Pavel
  • 1,278
  • 2
  • 17
  • 34
  • Possible duplicate of [Retrieve only the queried element in an object array in MongoDB collection](http://stackoverflow.com/questions/3985214/retrieve-only-the-queried-element-in-an-object-array-in-mongodb-collection) – styvane Jan 08 '16 at 08:15

1 Answers1

2

You can do this using aggregation pipeline

  • $unwind the translations array
  • Use $match to select the documents with code 'en'
  • Use $project to include or reset fields in your result.
    db.collection.aggregate(
        [
            { "$unwind": "$translations"}, 
            { "$match": { "translations.code": "en" }}, 
            { "$project": { "value": "$translations.value", "_id": 1 }}
       ]
    )
styvane
  • 59,869
  • 19
  • 150
  • 156