Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

196
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda