I have a mongodb document which looks like this:
document
title
suburb
id
date
And I want to add a search feature where people can search for documents via suburb and title. I am using the text search feature and I want something like this:
var search = {
$and : [
{ $search:'melbourne' }, // Search in suburb
{ $search:'hello world' } // As well as in title
]
};
db.ad.find(search).sort([['date', -1]]).limit(10).skip(0, callback);
But the above code is not working. I have indexed both suburb and title fields and enabled text search.
Does anyone know how to make a mongodb clause supporting text search for two different fields?
I am using mongojs with mongodb v 2.6
The "text search" concept in mongodb does not work like that. Instead the concept here is that you define "mutiple fields" in your "text index" and just search for the terms.
Let's say you have "stuff" like this:
{ "_id" : ObjectId("55ba22294bde97b581332979"), "title" : "Hello there" },
{ "_id" : ObjectId("55ba22414bde97b58133297a"), "title" : "Hello world" },
{
"_id" : ObjectId("55ba22594bde97b58133297b"),
"title" : "Hello world",
"suburb" : "melbourne"
}
Then I decide to create a text index like this:
db.junk.createIndex(
{ "title": "text", "suburb": "text" },
{ "weights": { "title": 10 } }
)
Then I do a search using $text
:
db.junk.find(
{ "$text": { "$search": "Hello World Melbourne" } },
{ "score": { "$meta": "textScore" } }
).sort({ "score": { "$meta": "textScore" } })
Which gives the results:
{
"_id" : ObjectId("55ba22594bde97b58133297b"),
"title" : "Hello world",
"suburb" : "melbourne",
"score" : 11.5
},
{
"_id" : ObjectId("55ba22414bde97b58133297a"),
"title" : "Hello world",
"score" : 1.5
},
{
"_id" : ObjectId("55ba22294bde97b581332979"),
"title" : "Hello there",
"score" : 1
}
Which "both" searches over all the fields specified in the index and also considers the additional "weight" as given to the "suburb" field in this case to make it an even more popular ranking.
So you don't use additional conditons in terms, you put "all" of the terms in the "one" text query string to search on multiple fields.
Your solution will not work if you want to apply text search on multiple fields.For that you need to create multiple indexes and declare multiple fields as "text".
It is done as:
db.yourcollectionname.ensureIndex({field1:"text",field2:"text", ...})
And then run the find query as :
db.yourcollectionname.find({$text:{$search:"keywords"}})
If still your text search does not work,I found this article very helpful
http://codewhoop.com/article/MongoDb%20Text%20Search%20in%20fields%20of%20document
It contains all the steps you need to follow ,to run your text search query successfully and also sort your results on the basis of their relevance.Hope it helps you :)