4

I'm trying to filter a MongoDB collection with a .find() query and run a text search on the results to lower the cost of the query but I can't seem to be able to chain the commands.

Here's what I've tried (that doesn't work):

db.jobs.find({
    "salary.max": {
        $gte: 50000,
        $lte: 120000
    }
}).runCommand("text", {
    search: "metal"
})

I've also tried the query in the reverse order, which defeats the purpose and doesn't work either.

Is there a way to chain a .runCommand() to a .find() in MongoDB?

1 Answer 1

5

the .find function returns a DBCursor which hasn't got a a .runCommand-function. So this obviously doesn't work.

But what does work is using your find-query in the text database command. As you can read in the documentation for text searching, you can pass a filteras an optional parameter to the text command. These filter documents work exactly like those you pass to find.

db.jobs.runCommand( "text", { 
    search: "metal",
    filter: { 
        "salary.max": {
            $gte: 50000,
            $lte: 120000
        }
    }
} );
Sign up to request clarification or add additional context in comments.

6 Comments

Can you also chain a location based query (2dsphere) to this?
@A.M.K I see no reason why it should not work. The geospatial operators like $nearSphere or $geoWithin are normal filter-operators, so you can add them to your filter document. And while the documentation points out that each collection can only have one text index and one geo index, it doesn't say anywhere that it can't have one of each.
OK, thank you. While I waited for an answer I played around with ElasticSearch a little and it looks like the extra coding trouble of switching will be worth it.
Why the hell is any of this necessary? Why isn't text search part of find()?
@light24bulbs I saw that you commented on this. I've since found that MongoDB is a fantastic database engine but it simply isn't made for searching. Elasticsearch takes a bit (a lot?) of time to setup but it's well worth it.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.