Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB: return a document if another does not exist

I am struggling to find a good way of executing a compound MongoDB find() with the following criteria:

  • Query will match one document based on search criteria
  • If a match is a found, that document will be returned
  • If a match is NOT found, another document would be returned in is place. This second document would match another set of criteria
  • The query would ideally return exactly one record no matter what.

In my particular case, I have a collection of users which contains a list of users and their associated permissions. It also contains a special entry for a guest pseudo-user that contain default permissions. This guest document is the one that needs to be returned if an exact user match does not take place.

I have tried using {$or: [ { id: "bob" }, {id: "guest" } ]} as well as { id: { $in: [ "bob", "guest" ] } }, but both of these search the collection sequentially and would return either "bob" or "guest" depending on which was inserted first.

Is there a way to explicitly say find bob or as a fallback, return the guest document?

Keep in mind this would be executed from Node.js, hence I'm looking for a clean & simple way to offload this to MongoDB.

I realize this can be done as two queries, but I would like to avoid that scenario if possible.

Thank you!

like image 364
mstubbies Avatar asked Jul 05 '26 06:07

mstubbies


1 Answers

if you insert guest as the first object, then by combination of limit and sort by _id you can solve this!

like image 125
Mohsen ZareZardeyni Avatar answered Jul 07 '26 10:07

Mohsen ZareZardeyni



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!