使用回调对查询中的结果进行排序和限制

时间:2014-03-16 19:07:31

标签: node.js mongodb mongoose

使用Mongoose,我想用MongoDB进行查询并订购并限制我得到的结果。我正在使用Node.js这样做,所以我使用回调。

到目前为止,我已经成功订购了我的结果:

  myModel.find({ $query: {}, $orderby: { created_at : -1 }}, function (err, items) {
    callback( null, items )
  });  

如何限制我选择的结果和索引以及我想要获得的项目数量?

2 个答案:

答案 0 :(得分:9)

使用mongodb native: http://mongodb.github.io/node-mongodb-native/api-generated/collection.html#find

myModel.find(filter)
            .limit(pageSize)
            .skip(skip)
            .sort(sort)
            .toArray(callback);

您还可以在查询中指定项目:

myModel.find(filter, {sort: {created_at: -1}, limit: 10}, function(err, items){

});

节点mongodb native中没有$ orderby,所以我不确定你正在使用哪个库或其他工具。

...

现在您已经澄清了Mongoose(我一般建议反对):

myModel.find(filter).limit(10).exec(function(err, items){
//process
});

答案 1 :(得分:2)

要对文档进行排序,我们可以在length (suc c)对象上应用sort。要强制执行排序顺序,而不是传递对象,我们需要将数组传递给cursor方法。

sort

需要注意的一点是 var MongoClient = require('mongodb').MongoClient, commandLineArgs = require('command-line-args'), assert = require('assert'); var options = commandLineOptions(); MongoClient.connect('mongodb://localhost:27017/crunchbase', function(err, db) { assert.equal(err, null); console.log("Successfully connected to MongoDB."); var query = queryDocument(options); var projection = { "_id": 0, "name": 1, "founded_year": 1, "number_of_employees": 1 }; var cursor = db.collection('companies').find(query); cursor.project(projection); cursor.limit(options.limit); cursor.skip(options.skip); cursor.sort([ ["founded_year", 1], ["number_of_employees", -1] ]); var numMatches = 0; cursor.forEach( function(doc) { numMatches = numMatches + 1; console.log(doc.name + "\n\tfounded " + doc.founded_year + "\n\t" + doc.number_of_employees + " employees"); }, function(err) { assert.equal(err, null); console.log("Our query was:" + JSON.stringify(query)); console.log("Documents displayed: " + numMatches); return db.close(); } ); }); function queryDocument(options) { console.log(options); var query = { "founded_year": { "$gte": options.firstYear, "$lte": options.lastYear } }; if ("employees" in options) { query.number_of_employees = { "$gte": options.employees }; } return query; } function commandLineOptions() { var cli = commandLineArgs([{ name: "firstYear", alias: "f", type: Number }, { name: "lastYear", alias: "l", type: Number }, { name: "employees", alias: "e", type: Number }, { name: "skip", type: Number, defaultValue: 0 }, { name: "limit", type: Number, defaultValue: 20000 }]); var options = cli.parse() if (!(("firstYear" in options) && ("lastYear" in options))) { console.log(cli.getUsage({ title: "Usage", description: "The first two options below are required. The rest are optional." })); process.exit(); } return options; } 适用MongoDBskiplimit

的顺序
  • sort
  • sort
  • skip

MongoDB skip, limit and sort order

如果我们设置了索引,我们也有可能在limit方面对数据进行排序。

请注意,MongoDB驱动程序将在调用传递回调函数的游标方法处理查询结果时发送查询。