I am looking for a way to sort results by value of a field while performing a full text search with mongodb 2.4.
My text search command looks something like this:
db.books.runCommand( "text", { search: "science" } )
What I would like to do is something like:
db.books.runCommand( "text", { search: "science", "sort": "rating" } )
I can see in the documentation that a limit parameter exists, but not something to sort results by other than the default sort by relevance score.
Re sorting the results is probably going to be inefficient. What is a good way to get this done?
Had the same problem, managed to solve the problem (pymongo) by using instead of the runCommand stuff the '$meta' operator:
# create text index
db.collection.ensure_index([("textField", "text")], name = "Text_search_index")
# query
queryDict = { "$text": { "$search": ""science"}}
# cursor
cursor = db.collection.find(queryDict, {'score': {'$meta': 'textScore'}, "_id":1}).sort([('score', {'$meta': 'textScore'})]).limit(limit_value)
Looks like this is available only from 2.6 version at least in pymongo
Also in Mongo shell this equivalent to :
db.collection.ensureIndex({"textField":"text"})
queryDict = { "$text": { "$search": "science"}}
db.collection.find(queryDict, {'score': {'$meta': 'textScore'}}).sort({'score': {'$met
a': 'textScore'}}).limit(100)
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