Pavel
Pavel

Reputation: 1288

Get specific fields with MongoDb query

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"
},....
...]

Upvotes: 0

Views: 69

Answers (1)

Sede
Sede

Reputation: 61225

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 }}
       ]
    )

Upvotes: 2

Related Questions