node.js - mongoose/mongodb 自定义排序

标签 node.js mongodb mongoose

我在 MongoDB 中有一个字符串类型的字段。它将包含一些字母和数字的组合,例如“10”、“101”、“11”、“112”、“x115”、“abc.5”。现在,如果我告诉 MongoDB 对这些进行排序,它将按字母顺序排序,排序如下:

  • 10
  • 101
  • 11
  • 112
  • abc.5
  • x115

它在“11”之前排序“101”,我如何更改排序以便数字正确排序?

最佳答案

您可能想要使用 db.eval 如果您决定在数据库端执行此操作。

Answer extracted from another question:

I don't think this is possible directly; the sort documentation certainly doesn't mention any way to provide a custom compare function.

You're probably best off doing the sort in the client, but if you're really determined to do it on the server you might be able to use db.eval() to arrange to run the sort on the server (if your client supports it).

Server-side sort:

db.eval(function() { 
  return db.scratch.find().toArray().sort(function(doc1, doc2) { 
    return doc1.a - doc2.a 
  }) 
});

Versus the equivalent client-side sort:

db.scratch.find().toArray().sort(function(doc1, doc2) { 
  return doc1.a - doc2.b 
});

关于node.js - mongoose/mongodb 自定义排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14720484/

相关文章:

javascript - 如何在 Nodejs 中循环调用异步函数

java - 如何在 mongodb 中使用 $and 运算符 - java 驱动程序

spring - 使用 _class 的 MongoDB 类型推断

javascript - 使用 mongo/mongoose 快速表达的全局变量

node.js - 如何与多个微服务共享 Mongoose 模型

node.js - 获取文档字段中存在的匹配数组元素,该字段也是一个数组

node.js - 是否有任何框架可以在 NodeJS 中创建适当的 REST(即超媒体)接口(interface)?

node.js - 池 Websocket 连接 - NodeJS

node.js - npm 错误 E401 : Unable to authenticate, 需要:基本领域 ="Sonatype Nexus Repository Manager"

r - Mongolite - 明显太大,16mb 上限