Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB Closest Match on properties

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?

like image 624
Thomas Avatar asked Feb 17 '18 17:02

Thomas


1 Answers

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)
like image 159
anhlc Avatar answered Oct 05 '22 00:10

anhlc