ac360
ac360

Reputation: 7835

How to do a MongoDB text search, with .skip(), .limit(), and total matching results in one query?

I am using MongoDB 2.6's text search with much success, but to add in Total Matching Results to my search response object, I have to perform a separate query. Is there a way to combine both of these into one query, perhaps using the aggregation framework?

Product.collection.find(
        { $text : { $search : query } },
        { score : { $meta: "textScore" } }
    )
    .sort({ score: { $meta : "textScore" } })
    .skip(0)
    .limit(20)
    .toArray(function(error, products) {
        if (error) {
            console.log(error);
        } else {
            Product.collection.count(
                { $text : { $search : query } }
            , function(err, count){
                if (error) {
                    console.log(error);
                } else {
                    console.log("Counts Match? : ", count, products.length)
                }
            });
        }
    });

Upvotes: 0

Views: 560

Answers (1)

aks
aks

Reputation: 720

@ac360, with v2.6 it should be possible to use $text in aggregation framework and adding a calculated column for {total: {$sum: 1}} in $group clause should serve what you are looking for. Please see through a couple of similar examples t http://docs.mongodb.org/manual/tutorial/text-search-in-aggregation/ .

Upvotes: 1

Related Questions