How to select all fields of parent and filter out some children keys with MongoDb (Filtered out Children)

Viewed 24

I have the following collection in MongoDB, it is a category collection supports multilingual category names.

I would like to get all parent fields plus the child object includes only given languages key value pairs

Say I only want "en" and "de" rows and not interested in other languages for the mlgCategoryName.

[
  {
    "catId": 1,
    "url": "",
    "tag": "",
    "mlgCategoryName": {
      "en": "Clothes",
      "de": "Kleidung"
    }
  },
  {
    "catId": 2,
    "url": "",
    "tag": "",
    "mlgCategoryName": {
      "en": "Toys",
      "de": "Spielzeug",
      "fr": "Jouet"
    }
  }
]

The desired result for "en" is:

[
  {
    "catId": 1,
    "url": "",
    "tag": "",
    "mlgCategoryName": {
      "en": "Clothes",
    }
  },
  {
    "catId": 2,
    "url": "",
    "tag": "",
    "mlgCategoryName": {
      "en": "Toys",
    }
  }
]

The desired result for "en" and "de" is:

[
  {
    "catId": 1,
    "url": "",
    "tag": "",
    "mlgCategoryName": {
      "en": "Clothes",
      "de": "Kleidung"
    }
  },
  {
    "catId": 2,
    "url": "",
    "tag": "",
    "mlgCategoryName": {
      "en": "Toys",
      "de": "Spielzeug",
    }
  }
]

select("-mlgCategoryName.fr") is good to eliminate given language, but I need the opposite; include only given languages for the child object(along with the all parent fields)

If I do select("mlgCategoryName.en") then overall result, this time, does not include parent fields but the mlgCategoryName with "en".

I beleive it can be resolved by aggregation but I dont know how to query for this type of result.

0 Answers
Related