I'm trying to implement a full text search with mongodb 3.4, nodejs and socket.io, with distinct and sorting. So far so good, i have this code that works fine but without the sorting part:
socket.on('searchProductName', function (data) {
MongoClient.connect(config.database.url, function (err, db) {
db.collection(config.database.collection.products).distinct('productName',
{
$text: {$search: data}}, {score: {$meta: "textScore"}
},
function (err, doc) {
socket.emit('searchProductNameResults', doc);
db.close();
});
});
});
I'm trying to find a way to use this based on textScore sorting method, but for distinct values:
db.collection.find(
<query>,
{ score: { $meta: "textScore" } }
).sort( { score: { $meta: "textScore" } } )
Any ideas?
Thank you
Use the aggregate() function in the aggregation framework to take advantage of the text search within the $match , $sort , and $group pipeline operators to help you achieve the desired result.
Take, for example, the following pipeline that uses the $match operator as the initial step and includes the $text operation. The score can be part of a $sort pipeline specification, and the above $group pipeline creates the various values sorted by the scores, using the $addToSet operator:
socket.on('searchProductName', function (data) { MongoClient.connect(config.database.url, function (err, db) { var pipeline = [ { "$match": { "$text": { "$search": data } } }, { "$sort": { "score": { "$meta": "textScore" } } }, { "$group": { "_id": null, "products": { "$addToSet": "$productName" } } } ]; db.collection(config.database.collection.products) .aggregate(pipeline, function (err, docs) { socket.emit('searchProductNameResults', docs[0].products); db.close(); } ); }); });