0

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 ?

1 Answer 1

3

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

For example I have this model:

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

And I want exclude key:3 and key5:

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

Now this query return a correct result:

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

I hope this solution helps you.

Sign up to request clarification or add additional context in comments.

1 Comment

Does this work for _ids too?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.