Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB: findOne with $or condition

Such request as db.collection.findOne({$or: [{email: '[email protected]'},{'linkedIn.id': 'profile.id'}]}); may return an array with two records.

Is it possible to specify to return only the first occurrence so that I always have a model as a response, not an array?

E.g. if there is a record with a specified email, return it and do not return another record, if any, matching profile.id?

Another question is if the order of the params 'email' and 'linkedIn.id' matters.

All this hazel is about LinkedIn strategy, which never returns an email (at least for me) but I have to cater for case when it may return an email. So I construct my query depending on email presence and if it is present, the query is with $or operator. But I would like to avoid checking for whether the response is an object or an array and then perform additional operation on array values to figure out which of the values to use.

like image 885
user2814599 Avatar asked Sep 01 '25 16:09

user2814599


1 Answers

According to documentation of mongo DB

findOne()

always returns a single document irrespective of matches it found. And regarding order of retrieval it will always return the first match except capped collection which maintains order of insertion of documents into collection.

For more detailed description about findOne please refer the documentation as mentioned in following URL

https://docs.mongodb.org/manual/reference/method/db.collection.findOne/

like image 189
Rubin Porwal Avatar answered Sep 04 '25 09:09

Rubin Porwal