Q: MongoDB use a field value in the sort function My MongoDB knowledge is pretty compact I would say but, in my MongoDb setup we save translations in an array. The problems is that I need to sort my titles on the original language code. So I want the originalLangCode value in the sort function.
So if I would to sort it only on the NL language. My query would be like this:
db.getCollection("name").find({}).sort({"translations.NL.title" : 1});

But what I actually want is something like :
 db.getCollection("name").find({}).sort({"translations.originalLangCode.value.title" : 1});

one of the records
So guys, any help would be appreciated!

A: It is not a good practice to have values as keys. When you use values as key it is hard to query against them, as in mongodb you can't pass values in key field.
If you have a limited no of language code(NL,DE) you can use below code to sort them according the originalLangCode.
db.getCollection('name').aggregate(
   [
      {
         $project: {
            id_: 1,
            corLang: 1,
            corLat: 1,
            translations: 1,
            orignalsort: {
               $concat: [{
                    $cond: [ { $eq: ["$originalLangCode", "NL"] }, "$translations.NL.title", "" ]
                  },{
                    $cond: [ { $eq: ["$originalLangCode", "DE"] }, "$translations.DE.title", "" ]
                  },{
                    $cond: [ { $eq: ["$originalLangCode", "FR"] }, "$translations.FR.title", "" ]
                  }]
            }
         }
      },
      {
        $sort: {orignalsort: 1}
      }
   ]
)

**The Above solution is for mongodb version less than 3.3.5 and you should use it as latest stable release is 3.2
From upcoming version 3.3.5 we can use the $switch operator, with switch solution will be like below code**
db.getCollection('name').aggregate(
   [
      {
         $project: {
            id_: 1,
            corLang: 1,
            corLat: 1,
            translations: 1,
            orignalsort: {
                $switch: {
                    branches: [
                        {
                            case: { $eq: ["$originalLangCode", "NL"] },
                            then: "$translations.NL.title"
                        },  
                        {
                            case: { $eq: ["$originalLangCode", "DE"] },
                            then: "$translations.DE.title"
                        },  
                        {
                            case: { $eq: ["$originalLangCode", "FR"] },
                            then: "$translations.FR.title"
                        },                   
                    ],
                    default: "$translations.NL.title"
                }
            }
         }
      },
      {
        $sort: {orignalsort: 1}
      }
   ]
)

I have tested first code on my local system, but haven't checked switch case. 
