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

123
Vistas
return what was not found in array in MongoDB

say my database collection has

* user collection*
[
{id:'1'}
{id:'2'}
]

I have an array of object

[
{id:'1'}
{id:'2'}
{id:'3'}
]

I want the object that was not found in the collection.

I want

[

{id:'3'}
]

I'm currently have this

 const records = await dbo
        .collection('user collection')
        .find({
          'id': { $in: newArr },
        })
        .toArray();

I'm a bit stumped on what to do! ... hope someone can help Thanks!

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Option 1:

Looks like this is what you need via the not in operation ( $nin ) when you need to check the not exisitng id in collection documents from provided array:

db.collection.aggregate([
 {
   $match: {
     id: {
      "$nin": [
         1,
         2
       ]
     }
   }
 },
 {
   $group: {
     _id: null,
     "idnotIntheArray": {
        $push: "$id"
      }
    }
  }
])

Explained:

  1. $match for any documents with id not in provided array.
  2. $group all id's in an array

plaground1


Option 2:

And this is the option where you output only the array elements not existing in the collection:

  db.collection.aggregate([
 {
   $group: {
     _id: null,
     ids: {
       $push: "$id"
     }
   }
 },
 {
  $project: {
  missingFromCollection: {
    "$setDifference": [
      [
        1,
        5,
        4
       ],
        "$ids"
      ]
     }
    }
  }
 ])

Explained:

  1. Push all id elements from collection to array ids ( note this solution will not allow more then 16MB total size of id's )
  2. Use $setDifference to identify the difference between the two arrays.

playground2

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can use this aggregation:

db.entity.aggregate([
    {
        $match : {
            "myObjList.id" : 1
        }
    },
    {
        $unwind : "$myObjList"
    },
    {
       $match : {
            "myObjList.id" : 1
        } 
    }
])

and my aggregation result:

{
    "_id" : ObjectId("6225a0f78d435fd2845f1dd1"),
    "myObjList" : {
        "id" : 1
    }
}
about 4 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 Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda