Let says I have a Users collection in MongoDB whose schema looks like this:
{
name: String,
sport: String,
favoriteColor: String
}
And lets say I passed in values like this to match a user on:
{ name: "Thomas", sport: "Tennis", favoriteColor:"blue" }
What I would like to do is match the user based off all those properties. However, if no user comes back, I would like to match a user on just these properties:
{sport: "Tennis", favoriteColor:"blue" }
And if no user comes back, I would like to match a user on just this property:
{ favoriteColor: "blue" }
Is it possible to do something like this in one query with Mongo? I saw the $switch
condition in Mongo that will match on a case and then immediately return, but the problem is that I can't access the document it would have retrieved in the then
block. It looks like you can only write strings in there.
Any suggestions on how to accomplish what I'm looking for?
Is the best thing (and only way) to just execute multiple User.find({...})
queries?
This is a good case to use MongoDB text index:
First you need to create text index on those fields:
db.users.ensureIndex({ name: "text", sport: "text", favoriteColor: "text" });
Then you can search the best match with "$text" limited by a number to show:
db.users.find( { $text: { $search: "Tennis blue Thomas" } } ).limit(10)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With