Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

node.js - mongoose/mongodb custom sort

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

It orders "101" before "11", how could I change the sorting so that numerals are ordered properly?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You might want to use db.eval if you are determined to do this on the database-side.

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 
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...