How to check if list of field values exists in db mongodb

Viewed 906

I want to know if there is a way to find if the array of string values exists as individual field values in collections in mongodb?

For example I have the following schema

user:[{name:'abc',email:'email1'},{name:'efg',email:'email2'},{name:'hij',email:'email3'},{name:'zyx',email:'email4'}]

Now if I have an array of emails, say arr=['email1','email3']

Then I want to check if these emails of the array already exists as email value in the user schema. Is there a way I can do this with just one query? As right now I am iterating through the array and checking if emails exists one by one, but if array is too large it takes too much time.

Note: I want to just check if all these emails in array exists in collection and not just one or two of the emails. All the emails in that array should be present, if anyone of the emails is not present I should get to know

Like for example if i do the following

const data= db.users.checkAllEmails(array); // query function which needs to be implemented 

and if I check if(data.length===array.length) then this should return true.

1 Answers

You can use $in

db.collection.find({
  email: {
    $in: [
      "email3",
      "email4"
    ]
  }
})

Working Mongo playground

Related