【问题标题】:Query and Sorting collection MongoDB Stitch查询和排序集合 MongoDB Stitch
【发布时间】:2020-01-21 06:56:54
【问题描述】:

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

例如,如果我搜索 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 缝合文档中没有找到任何示例。

有什么建议吗?

【问题讨论】:

    标签: mongodb sorting find meta mongodb-stitch


    【解决方案1】:

    它的崩溃说'未知运算符 $meta'。在 mongodb 缝合文档中没有找到任何示例。

    有几种方法可以做到这一点。其中一种方法是创建一个可以从您的应用程序 (React) 调用的Stitch Function。在你的函数中,你可以调用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}
    

    请注意,要执行text search 查询,您必须在集合上有一个text index

    【讨论】:

      猜你喜欢
      • 2016-05-02
      • 2018-08-09
      • 1970-01-01
      • 2015-06-14
      • 1970-01-01
      • 1970-01-01
      • 2019-04-12
      • 2017-09-15
      • 1970-01-01
      相关资源
      最近更新 更多