Question

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?

Was it helpful?

Solution

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
        }
    }
} );
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top