N
N
Nam Zanilla2022-02-13 15:46:59
MongoDB
Nam Zanilla, 2022-02-13 15:46:59

Is it possible to substitute a variable in MongoDB aggregation?

There is a collection Languages

[
    {
        "code": "ru",
        "name": {
            "ru":  "Русский",
            "en": "Russian"
        }
    },
    {
        "code": "en",
        "name": {
            "ru":  "Английский",
            "en": "English"
        }
    }
]


You need to choose languages ​​to get an object
[
    {
        "code": "ru",
        "name": ''Русский'
    },
    {
        "code": "en",
        "name": "English"
    }
]


const $project = {
      name: {
        $switch: {
          branches: [
            {
              case: { $eq: [ '$code', 'en' ] },
              then: '$name.en'
            },
            {
              case: { $eq: [ '$code', 'ru' ] },
              then: '$name.ru'
            }
          ]
        }
      },
      code: '$code'
    }

const pipeline = [ { $project } ]
const result = await LanguagesModel.aggregate(pipeline)


The problem is that when adding a new language, you will have to add switch, and the option suggests itself with substituting code in name, but I don’t know if this is possible

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Rag'n' Code Man, 2022-02-14
@iDmitriyWinX

class Language {
     code: 'ru' | 'en';

     @Transform(prop => ({code: prop.obj.code, name: prop.value[prop.obj.code]}))
     name: { en: string, ru: string }
}

const languages = await LanguagesModel.find();

const result = plainToInstance(Language, languages)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question