• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Evaluaciones
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

95
Vistas
Mongodb, query within key-pair values

Is there any way to query inside this struture by the object keys of roles?

   interface UsersModel{
         _id: string;
         email: string;
         roles: { [key: string]: RolesType[] };
    }

For now I get the data into users like:

roles: {
   $ne: null
}

and then

const finalResult = users.filter(u => Object.keys(u.roles).includes('objectKeyIwant'));

Can this be done on the mongodb side and avoid getting all the data then filter it?

Data examples: The user collection is like this:

{
    _id: '610baff85c071a2bd59dc84f',
    email: 'some@email.com',
    roles : {
        "shop1" : [ 
            "shop_stock_manager"
        ],
        "shop2" : [ 
            "shop_admin", 
            "shop_stock_manager"
        ]
    }
}

And I want to get all the users that have any role in shop2.

almost 3 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

use this

db.collection.find({"roles.shop2":{$ne:[]}})
almost 3 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda