Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a mongo collection where i have below structure:

{
   "feature":"abc",
   "translations"[
      {
         "lang":"en",
         "text":"This is my text in english"
      },
      {
         "lang":"de",
         "text":"This is my text in german"
      }
   ]
},
{
   "feature":"cde",
   "translations"[
      {
         "lang":"en",
         "text":"This is my text in english"
      }
   ]
}

Now, i want to write query to return default language "en" text if particular language ie., de text not found for a particular feature. If both language texts present, only "de" lang text need to be returned and "en" need to be ignored.

I tried with $or or $in, but these are giving both lang texts if present for a feature. I'm okay to do minimal changes to mongo document structure if required for better results.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
337 views
Welcome To Ask or Share your Answers For Others

1 Answer

The way I've think for this is using aggreagtion creating an auxiliar array (to get data easier) where is stored the transalation in desired language.

If the array is not empty, language exists, so the output is that value, otherwise, language will be english.

This is the query I've done, hope it helps.

  • First create a new filed using $set filtering values where "language = de". Using aggregation is neccesary use $filter because $elemMatch is not allowed.
  • Then, the next stage can use our auxiliar array to get $size and values. If the auxiliar array has not values (size is 0) then the desired language is english, stored in $translations.text. Else the language will be that one stored in the auxiliar array.
db.collection.aggregate([
  {
    "$set": {
      "aux_translations": {
        "$filter": {
          "input": "$translations",
          "as": "l",
          "cond": {"$eq": ["$$l.lang","de"]}}
      }
    }
  },
  {
    "$project": {
      "translation": {
        "$cond": {
          "if": {"$eq": [{"$size": "$aux_translations"},0]},
          "then": {"$arrayElemAt": ["$translations.text",0]},
          "else": {"$arrayElemAt": ["$aux_translations.text",0]}
        }
      }
    }
  }
])

Example here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...