Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

199
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda