Reputation: 6013
I am trying to check my collection to return all documents where an element of the array in the document is a certain value.
For example, here is one of my documents JSON:
[
{
"employer" : "[email protected]",
"applicants" : [
{
"email" : "[email protected]"
},
{
"email" : "[email protected]"
}
]
},
{
"employer" : "[email protected]",
"applicants" : [
{
"email" : "[email protected]"
}
]
},
{
"employer" : "[email protected]",
}
]
Now, what I would like returned is any document where the applicants array does not contain the email "[email protected]"
OR where there is no applicants array
.
In my example JSON above, it should return the documents for employer1
and employer2
.
I have gotten as far as to return the documents where the applicant [email protected] does not exist
, so employer1, but I don't understand how I can also include the employer3
. How can I do this?
This is my query so far in JavaScript:
collection.find({"applicants.email" : {$ne : req.user.username}}, {}, function(e,docs){
res.json(docs);
console.log(docs);
});
Upvotes: 2
Views: 1104
Reputation: 2766
Try the following query, which may help you:-
Refer $size for more info on how to use it.
This query will return results, if applicants.email
not equal to req.user.username
OR if applicants
array size is 0.
collection.find({$or:[
{"applicants.email" : {$ne : req.user.username}},
{applicants: {$size: 0}}
}], function(e,docs){
console.log(docs);
});
I never tried the query. Let me know if it is giving any error.
Also you can try out this one:-
This query will return results, if applicants.email
not equal to req.user.username
OR if applicants
array is not present.
collection.find({$or:[
{"applicants.email" : {$ne : req.user.username}},
{applicants: {$exists: false}}
}], function(e,docs){
console.log(docs);
});
Refer $exists for more info.
Hope it will help.
Upvotes: 1
Reputation: 910
just try this query , $nin
is useful for this condition
collection.find({"applicants.email" : {$nin:["[email protected]"]}}, {}, function(e,docs){
res.json(docs);
console.log(docs);
});
Upvotes: 0
Reputation: 615
Try This:
collection.find({applicants: {$not: {$size: 0}}},function(err,data){
if(err){
console.log(err);
}
else{
console.log("Applicats Array Where size is not zero:");
console.log(data);
}
});
Upvotes: 0