mongodb - Select nested fields in mongo db -
i have collection in mongodb fields nested under language root:
{     en: {         title: "eng title",         content: "eng content",     },     it: {         title: "it title",         content: "it content"     }     //common attributes languages     images: {         mainimage: "dataurl",         thumbimage: "dataurl"     } } i have variable called 'currentlang'; need find document title selecting "currentlang" object , common fields (images in example); "currentlang" object, have output document not nested; example, having currentlang = "en"
desired output:
{     title: "eng title",     content: "eng content",     images: {         mainimage: "dataurl",         thumbimage: "dataurl"     } } is possible?
you need aggregate below:
- construct findobject match records containing($exists) language.
- construct projectionobject project 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} ]) 
Comments
Post a Comment