user2814599
user2814599

Reputation: 1190

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.

Upvotes: 4

Views: 9942

Answers (2)

Rubin Porwal
Rubin Porwal

Reputation: 3845

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/

Upvotes: 3

Sven
Sven

Reputation: 5265

According to the MongoDB docs for db.collection.findOne():

Returns one document that satisfies the specified query criteria. If multiple documents satisfy the query, this method returns the first document according to the natural order which reflects the order of documents on the disk. In capped collections, natural order is the same as insertion order. If no document satisfies the query, the method returns null.

You can't recieve multiple records from db.collection.findOne(). Are you sure you're not using db.collection.find()?

Upvotes: 0

Related Questions