mongoose/mongodb custom sort

后端 未结 2 644
南方客
南方客 2021-01-25 23:47

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

2条回答
  •  执念已碎
    2021-01-26 00:49

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

提交回复
热议问题