Select nested fields in mongo db

前端 未结 2 2030
醉酒成梦
醉酒成梦 2020-12-20 21:08

I have a collection in mongodb where fields are nested under a language root:

{
    en: {
        title: \"eng title\",
        content: \"eng content\",
            


        
2条回答
  •  旧时难觅i
    2020-12-20 21:27

    You need to aggregate as below:

    • Construct a find object to match only the records containing($exists) the language.
    • Construct a Projection object to project the fields.

    Code:

    var currentLang = "en";
    var project = {};
    project["title"] = "$"+currentLang+".title";
    project["content"] = "$"+currentLang+".content";
    project["images"] = 1;
    
    var find = {};
    find[currentLang] = {"$exists":true};
    
    db.collection.aggregate([
    {$match:find},
    {$project:project}
    ])
    

提交回复
热议问题