Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

200
Views
Full text search in MongoDB and NodeJS with text score sorting in distinct values

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

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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(); } ); }); });
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!