Select nested fields in mongo db

前端 未结 2 2021
醉酒成梦
醉酒成梦 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条回答
  • 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}
    ])
    
    0 讨论(0)
  • 2020-12-20 21:51

    I'm not sure how you're querying, so I'll assume you're going directly through the mongo client. Assuming you have defined a variable

    >currentLang = "en";
    

    You can run an aggregation operation and using the $project operator, restructure the presentation of the document.

    Here's an example that I've tested:

    > db.test.aggregate({$project: 
            {_id: 0, 
             title: "$" + currentLang + ".title", 
             content: "$" + currentLang + ".content", 
             images: 1
            }
        }).pretty();
    {
        "images" : {
            "mainImage" : "dataURL",
            "thumbImage" : "dataURL"
        },
        "title" : "eng title",
        "content" : "eng content"
    }
    

    If you want to combine this with an actual query, you can just include it as a $match operator, something like:

    > db.test.aggregate(
        {$match: 
            {"en.title": "eng title"}
        }, 
        {$project: 
            {_id: 0, 
             title: "$" + currentLang + ".title", 
             content: "$" + currentLang + ".content", 
             images: 1
            }
        }).pretty();
    
    0 讨论(0)
提交回复
热议问题