0

Every user has a mobile number, and I want to check there are other users in my address book.

So I have 1000 numbers and I want to check if any of the is in the database, so my initial idea is that for each number I run a mongodb query:

for (var i=0; i < numbers.length; i++) {
  db.users.findOne({phoneNumber: numbers[i]});
}

however I have been suggested to do so:

db.users.find($or: numbers.map(function(number){return {phoneNumber: number}}));
// That would result into a
// db.users.find($or:[{phoneNumber: "123"}, {phoneNumber: "234"}...])

Now are the two equivalent? Is the second way more expensive?

1 Answer 1

4

Using $in would be the cleanest way to find the docs where phoneNumber appears in numbers:

db.users.find({phoneNumber: {$in: numbers}})
Sign up to request clarification or add additional context in comments.

3 Comments

apparently if numbers.length == 500 it takes at least 30s
@haskellguy is that your own results or just heresay? At any rate $in will be more efficient than $or as the latter is exclusive. The main performance factor will be how many numbers you have in the array of the documents in the collection,
what kind of complexity does $in has? assuming I have n documents and m elements in the array?

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.