猫鼬/mongodb自定义排序 [英] mongoose/mongodb custom sort
问题描述
我在MongoDB中有一个字符串类型的字段.它将包含字母和数字的某种组合,例如"10","101","11","112","x115","abc.5".现在,如果我告诉MongoDB对它们进行排序,它将按照字母顺序进行排序:
I have a field in MongoDB that is a String type. It will contain some combination of letters and numbers like "10", "101", "11", "112", "x115", "abc.5". Right now if I tell MongoDB to sort these it will do an alphabetical sort, ordering as so:
- 10
- 101
- 11
- 112
- abc.5
- x115
它在"11"之前订购"101",我该如何更改排序方式以便正确地对数字进行订购?
It orders "101" before "11", how could I change the sorting so that numerals are ordered properly?
推荐答案
You might want to use db.eval
if you are determined to do this on the database-side.
我认为这不可能直接实现; 排序 文档 当然没有提及提供自定义比较的任何方式 功能.
I don't think this is possible directly; the sort documentation certainly doesn't mention any way to provide a custom compare function.
您最好在客户端进行排序,但是如果您
真正下定决心要在可以使用的服务器上进行操作
db.eval()
安排在服务器上运行排序(如果您的客户端
支持它.)
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).
服务器端排序:
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
});
这篇关于猫鼬/mongodb自定义排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!