Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

191
Vistas
how to get items from an object array in mongodb

my db collection is like

 {  "_id" : "57f4c1323eb5c694041ghea3",
 "example" : [ 
    {
        "exId" : "57f4c0d43eb5c694041fdebd",
        "_id" : ObjectId("57f4c1323eb5c694041fded2"),
        "projects" : [ 
            "57f4c1303eb5c694041fdec6"
        ]
    }, 
    {
        "exId" : "57f24ee56da92f9c19b0efd4",
        "_id" : ObjectId("57f4cfa93eb5c694041fdf4c"),
        "projects" : [ 
            "57f4cfa83eb5c694041fdf45"
        ]
    }, 
    {
        "exId" : "57f24ec16da92f9c19b0efcd",
        "_id" : ObjectId("580864867a36f5bc1058c2c8"),
        "projects" : [ 
            "580864837a36f5bc1058c2a9", 
            "57f4c1303eb5c694041fdec6"
        ]
    }
],

I need to get output as

"example": [
{
  "exId": "57f24ee56da92f9c19b0efd4",
  "_id": "57f4cfa93eb5c694041fdf4c",
  "projects": [
    "57f4cfa83eb5c694041fdf45"
  ]
},
{
      "exId" : "57f24ec16da92f9c19b0efcd",
      "_id" : ObjectId("580864867a36f5bc1058c2c8"),
      "projects" : [ 
          "580864837a36f5bc1058c2a9", 
          "57f4c1303eb5c694041fdec6"
      ]
  }
 ]
 }

where my query is

     db.userDb.findOne({ '_id': req.params.userId }, { example: { $elemMatch: { exId: { $in: accIds } } } })

and accIds is an array contains values "57f24ec16da92f9c19b0efcd", "57f24ee56da92f9c19b0efd4", "57f24fa26da92f9c19b0f005"

but my ouput is

"example": [
{
  "exId": "57f24ee56da92f9c19b0efd4",
  "_id": "57f4cfa93eb5c694041fdf4c",
  "projects": [
    "57f4cfa83eb5c694041fdf45"
  ]
}

],

any help is appreciated

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

db.collection.aggregate([
            { $unwind: '$example' },
            { $unwind: '$example.projects' },
            { $match: { 'example.exId': { $in: accIds} } },
            { $group: { _id: null, projectList: { $addToSet: '$example.projects'  } } },
        ])

Hope this will work.

over 4 years ago · Santiago Trujillo 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 Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda