【问题标题】:How to multi-sort with strings and multiple types in MongoDB (JS)?如何在 MongoDB(JS)中对字符串和多种类型进行多重排序?
【发布时间】:2019-01-18 23:11:43
【问题描述】:

我如何按 str !null && exists >> bool 为真 >> createDate 是从最新的 到最旧的排序,因为命令?

这是我尝试过的:

// -1 = descending/newest, right?
var sort = 
{
    "str" : -1, // str will either null, "" or "filled". I don't think this works.
    "bool" : -1,  // bool will be true or false. Seems to maybe work.
    "createDate" : -1 // date obj. Seems to work.
};

【问题讨论】:

    标签: javascript mongodb sorting nosql


    【解决方案1】:

    您问题中的前两个条件实际上是过滤记录,第三个条件是对结果集进行排序。试试这个查询。

    db.collection.find({'str':{$ne:null,$exists:true},'bool':true}).sort({'createDate' : -1})
    

    【讨论】:

    • 谢谢,但我不确定你是否理解这个问题:在 OP 中,我输入 var sort 以暗示它是它自己的排序对象。我正在尝试多排序,而不是过滤。按 A、B、C 过滤。
    【解决方案2】:

    正确答案是 bool 有效,createDate 有效,但 str 无效:

    我发现 bool 和 createDate 过滤得很好——只是字符串没有。如果 str 存在,我制作了一个脚本来遍历我的所有数据库以添加一个 bool(并添加到脚本中以供将来使用)。

    因此:

    // -1 = descending/newest
    var sort = 
    {
        "strExistsBool" : -1,
        "bool" : -1,
        "createDate" : -1
    };
    

    然后使用:

    db.collection.find(someQuery).sort(sort)
    

    【讨论】:

      猜你喜欢
      • 2020-01-21
      • 2011-10-21
      • 2018-10-10
      • 2018-09-02
      • 2020-05-29
      • 1970-01-01
      • 2021-03-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多