angularjsnode.jsmongodbmongodb-querydebug-mode

Get exect match and matched data from mongodb using $text


I am trying to use the following query in MongoDB.
1) db.products.createIndex({ name: "text",category.name':"text"})
this will create a Index.

2) Now my query is
db.products.find({$text:{$search:"Sun moon Tapestry"}})
this will bring data according to Sun,moon, and Tapestry.

3) but i want to get data like this.
      a) first all data row in exect match Sun moon Tapestry
      b) then after that Sun,moon and Tapestry will show up

(NOTE: DB call should be one time)


Solution

  • You can use the matching textScore to sort the resultset:

    db.products
           .find({ $text : { $search : "Sun moon Tapestry" } }, { score: { $meta: 'textScore' } })
           .sort({score:{$meta: "textScore"}})
    

    Since you have 2 text indexes you can also define weights for name and category.name. https://docs.mongodb.com/v3.2/tutorial/control-results-of-text-search/

    PS:There is nothing related angularjs

    EDIT: if you use Mongoose the query stays the same, you have to query your model

    YourProduct
           .find({ $text : { $search : "Sun moon Tapestry" } }, { score: { $meta: 'textScore' } })
           .sort({score:{$meta: "textScore"}})
           .exec(function (err, data) {
                if (err)
                    res.json(err);
                else {
                    res.json(data)
                }
            });
    

    For the angular integration you can create a Service which uses $http https://docs.angularjs.org/api/ng/service/$http and do your ajax call.