Shaon Debnath
Shaon Debnath

Reputation: 117

Query and Sorting collection MongoDB Stitch

I am using react native and mongoDB stitch. My intention is, when I run query with a keyword, the result should be sorted with most match with keyword,

As example, If I search for Aqua, the result should be sorted as

I found a documentation for this (https://docs.mongodb.com/manual/reference/operator/projection/meta/)

db.collection.find(
   <query>,
   { score: { $meta: "textScore" } }
).sort( { score: { $meta: "textScore" } } )

But can not find how to write this code for mongodb stitch,

I have tried as

const query = {
        name: {
            $regex: searchKeyword,
            $options: 'i', 
            //"$meta": "textScore"
        },
        score: { "$meta": "textScore" } // not sure where to put it , Saying unknown operator $meta 
    };
const options = {
        "sort": { "score": { $meta: "textScore" }}
    };

db.collection(itemNameDB).find( query, options).toArray()
            .then(results => {
            console.log(results)
})

Its crashing saying 'unknown operator $meta'. Did not find any example in mongdb stitch documentation.

Any suggestion?

Upvotes: 0

Views: 160

Answers (1)

Wan B.
Wan B.

Reputation: 18835

Its crashing saying 'unknown operator $meta'. Did not find any example in mongodb stitch documentation.

There are a few ways of doing this. One of the ways, is to create a Stitch Function that could be called from your application (React). In your function, you can call db.collection.find(). For example:

exports = function(word){

     var coll = context.services.get("mongodb-atlas").db("dbName").collection("collName"); 
     var doc = coll.find(
        {"$text": {"$search": word}}, 
        {"score": {"$meta": "textScore"}}
     ).sort(
        {"score":{"$meta":"textScore"}}
     ).toArray();

     doc.forEach(element => console.log(JSON.stringify(element)));

     return doc; 
};

This function above should print out something similar to below, and returning the array in EJSON format.

{"_id":"5e262bf99514bb2d81bb8735","item":"Aqua","score":1.1}
{"_id":"5e262c009514bb2d81bb8736","item":"Aquae","score":1}
{"_id":"5e262c109514bb2d81bb8739","item":"Aqua-water","score":0.75}

Please note that to perform text search queries, you must have a text index on the collection.

Upvotes: 0

Related Questions