Home > OS >  How to exclude array of ids from query
How to exclude array of ids from query

Time:05-29

I have an array of _ids and I want to exclude them from the query:

console.log('relatedCards', relatedCards);
const motherCards = await db.MotherCard.find({ "_id": { $ne : relatedCards } });

But it returns this error:

no

Why this is happening and how to fix this ?

CodePudding user response:

$ ne is usually used for a value. But if you want to exclude multiple items in array, you can use $ nin

for example i've this model:

{
  "_id": "5a934e000102030405000000",
  "key": 1
},
{
  "_id": "5a934e000102030405000001",
  "key": 2
},
{
  "_id": "5a934e000102030405000002",
  "key": 3
},
{
  "_id": "5a934e000102030405000003",
  "key": 4
},
{
  "_id": "5a934e000102030405000004",
  "key": 5
}

And i wana exclude key:3 and key5 :

db.collection.find({
key: {
  "$nin": [
    3,
    5
  ]
}
})

now this query return correct result :

[
  {
    "_id": "5a934e000102030405000000",
    "key": 1
  },
  {
    "_id": "5a934e000102030405000001",
    "key": 2
  },
  {
    "_id": "5a934e000102030405000003",
    "key": 4
  }
]

I hope this solution helps you.

  • Related