digit
digit

Reputation: 4565

How to filter multiple criteria with not in nodejs & mongodb

I'm using nodejs and mongodb. In mongo db, there is users collection where the attributes are name and status. Status records have 'A', 'B', 'C' and 'D'. I want to filter record within name array and status except 'A'. How to do it?

var nameArr = [];
nameArr.push('Jojo');
nameArr.push('Legend');

// The record return null when i added status: !'A'
db.collection('users').find({name: {$in: nameArr},{status: !'A'}}).toArray(function (resp) {
     res.json({code: '00', content: resp});
});

User Schema

{
  "_id": ObjectId("515fd5f42a84cb610eed23es"),
  "name": "Jojo",
  "status": "A"
}
{
  "_id": ObjectId("584fd5f42a84cb610eed23ef"),
  "name": "Legend",
  "status": "C"
}
{
  "_id": ObjectId("585fd5f42a84c1110eed23ef"),
  "name": "Mark",
  "status": "D"
}
{
  "_id": ObjectId("585fd5ss42a84cb610eed23ee"),
  "name": "Swish",
  "status": "B"
}

Expected Output

{
  "_id": ObjectId("584fd5f42a84cb610eed23ef"),
  "name": "Legend",
  "status": "C"
}

Upvotes: 0

Views: 1951

Answers (2)

Dhruv
Dhruv

Reputation: 173

You can use $ne operator:

Probable query:

db.collection('users').find({name: {$in: nameArr}, status: { $ne:  'A' }}).toArray(function (resp) {
     res.json({code: '00', content: resp});
});

Upvotes: 1

Ravi Shankar Bharti
Ravi Shankar Bharti

Reputation: 9268

You are going on right track but "!" doesnt work in MongoDb.

You can use $ne for this:

db.collection('users').find({name: {$in: nameArr},status: { $ne :'A'}}).toArray(function (resp) {
     res.json({code: '00', content: resp});
});

$ne is an operator for checking Not Enquals to in mongoDb.

For more info please go through MongoDB $ne Documentation

Hope this helps!

Upvotes: 1

Related Questions