I have a collection in mongodb where fields are nested under a language root:
{
en: {
title: "eng title",
content: "eng content",
},
it: {
title: "it title",
content: "it content"
}
//common attributes for all languages
images: {
mainImage: "dataURL",
thumbImage: "dataURL"
}
}
I have a variable called 'currentLang'; I need to find a document by title selecting only the "currentLang" object and the common fields (images in this example); but for the "currentLang" object, I would like to have the output document not nested; for example, having currentLang = "en"
desired output:
{
title: "eng title",
content: "eng content",
images: {
mainImage: "dataURL",
thumbImage: "dataURL"
}
}
Is this possible?
You need to aggregate as below:
find
object to match only the records containing($exists) the language.Projection
object to project the fields.Code:
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
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:
If you want to combine this with an actual query, you can just include it as a $match operator, something like: