查询和排序集合 MongoDB Stitch



我正在使用 react native 和 mongoDB stitch。 我的目的是,当我使用关键字运行查询时,结果应该以与关键字最匹配的方式排序,

例如,如果我搜索 Aqua, 结果应排序为

  • 阿奎
  • 阿奎蒂卡
  • 水生提取物
  • -水
  • 等。

我找到了这方面的文档(https://docs.mongodb.com/manual/reference/operator/projection/meta/(

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

但是找不到如何为mongodb针迹编写此代码,

我已经尝试过

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)
})

它的崩溃说"未知操作员$meta"。在 mongdb 针迹文档中找不到任何示例。

有什么建议吗?

它的崩溃说"未知运算符$meta"。在 mongodb 针迹文档中找不到任何示例。

有几种方法可以做到这一点。其中一种方法是创建一个可以从您的应用程序 (React( 调用的 Stitch 函数。 在你的函数中,你可以调用db.collection.find((。例如:

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; 
};

上面的这个函数应该打印出类似于下面的内容,并以 EJSON 格式返回数组。

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

请注意,要执行文本搜索查询,您必须在集合上具有文本索引。

最新更新