user2573690 user2573690 - 6 months ago 27
Javascript Question

How to find if element exists in document - MongoDB?

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" : "employer1@gmail.com",
"applicants" : [
{
"email" : "joe@gmail.com"
},
{
"email" : "fred@gmail.com"
}
]
},
{
"employer" : "employer2@gmail.com",
"applicants" : [
{
"email" : "steven@gmail.com"
}
]
},
{
"employer" : "employer3@gmail.com",
}
]


Now, what I would like returned is any document where the applicants array does not contain the email
"steven@gmail.com"
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
steven@gmail.com 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);
});

Answer

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.