[英]Query and Sorting collection MongoDB Stitch
I am using react native and mongoDB stitch.我正在使用 react native 和 mongoDB 针法。 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例如,如果我搜索 Aqua,结果应排序为
I found a documentation for this ( https://docs.mongodb.com/manual/reference/operator/projection/meta/ )我找到了一个文档( 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,但是找不到如何为mongodb缝写这段代码,
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'.它的崩溃说'未知的运营商$meta'。 Did not find any example in mongdb stitch documentation.在 mongdb 针迹文档中没有找到任何示例。
Any suggestion?有什么建议吗?
Its crashing saying 'unknown operator $meta'.它的崩溃说'未知的运营商$meta'。 Did not find any example in mongodb stitch documentation.在 mongodb 针迹文档中没有找到任何示例。
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).其中一种方法是创建一个可以从您的应用程序(React)中调用的缝合函数。 In your function, you can call db.collection.find() .在您的函数中,您可以调用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.上面的这个函数应该打印出类似于下面的内容,并以EJSON格式返回数组。
{"_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.请注意,要执行文本搜索查询,您必须在集合上有一个文本索引。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.