My product catalog has items like this:
[ { "title": "A great Item", "ltitle": "a great item", "brand": { "name": "MyBrand" }, "description": [ { "lang": "en-en", "full": "<p>Super great item bla bla bla super great bla bla</p>", "short": "Super great item..." }, { "lang": "es-es", "full": "<p>Producto de muy alta calidad bla bla bla alta calidad etc</p>", "short": "Producto de muy..." } ] }, ... ]
I read about $ elemMatch , but I'm not sure if this is what I am looking for.
I would like to highlight the entire element, but only localized strings in description .
I tried without success:
db.items.find({description: { $elemMatch: { lang: "en-en" } } })
It returns the whole item with both languages in the description.
I also wonder what will happen to elements that do not have the selected language localization (it should be possible to choose the default language).
Also tried:
db.items.find({ "description.lang": "en-en"}, { _id:0, description: { $elemMatch: { lang: 'en-en' } } })
and
db.items.aggregate([ { $match: { 'description.lang': 'en-en' } }, { $project: { description: { $filter: { input: '$description', as: 'desc', cond: { $eq: [ '$$desc.lang', 'en-en'] } } }, _id:0 } } ])
But both of them just return a description , not the other fields of the collection of elements.
To expand my question, I would also like to know if it is possible to select only localized text in several fields:
[ { "title": [ { "lang": "en-en", "title": "A great Item" }, { "lang": "es-es", "title": "Un gran producto" }, ], "description": [ { "lang": "en-en", "full": "<p>Super great item bla bla bla super great bla bla</p>", "short": "Super great item..." }, { "lang": "es-es", "full": "<p>Producto de muy alta calidad bla bla bla alta calidad etc</p>", "short": "Producto de muy..." } ] } ]
I would like to select the entire element, but with texts in a localized language.
Is it possible? If not, how is it allowed? (I think, perhaps, in separating localized subdocuments and filling them out after selecting, or, possibly, the map reduction function? I also wonder how this will affect performance).
I look in different articles, and this is confusing: there seems to be no consensus on this topic.
Some of them choose a separate collection with translations (which seems to make it difficult to save deleted texts), others, choosing whole texts and filtering them (which seems like a bad option if there are several languages: many messages are processing) or even send them to the client (which seems inefficient to send so much unused data).