Home > Net >  return what was not found in array in MongoDB
return what was not found in array in MongoDB

Time:03-07

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!

CodePudding user response:

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

CodePudding user response:

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
    }
}
  • Related