我在 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/