本文的查询是指存储了5个手机数据后再查询。存储实现见文章:【Node.js】mongoose教程–存储 。
GitHub源码链接:sodino#MongoDemo 
排序文档链接 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 Query#sort(arg)     Sets the sort order Parameters:     arg <Object, String> Returns:     <Query> this       If an object is passed, values allowed are asc, desc, ascending, descending, 1, and -1. If a string is passed, it must be a space delimited list of path names. The sort order of each path is ascending unless the path name is prefixed with - which will be treated as descending. Example // sort by "field" ascending and "test" descending query.sort({ field: 'asc', test: -1 });    // equivalent query.sort('field -test'); Note:Cannot be used with distinct() 
上面的文档简单来说,就是排序的关键字是asc、desc、ascending、descending,用数字表示则是1升序,-1降序,或者可以直接在关键字段的前面加上-号表示降序。
以下给出排序的应用:
找出最贵、最便宜的手机:
下代码按price排序后,调用limit(1),限定了只取第一个查询结果的对象,所以exec(callback)中callback获取到的phones虽然是个Array但是是length为1。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 // Query.sort('-price')   // Query.sort({price : 'desc'}})    // Query.sort({price : 'descending'}})    // Query.sort({price : -1}}) // 查询结果按price数值降序排列 // Phone.find({}).sort('-price').exec((err, phones)=>{ // 	console.log(phones); // }); // Phone.find({}).sort({price : 'desc'}).exec((err, phones)=>{ // 	console.log(phones); // }); // Phone.find({}).sort({price : 'descending'}).exec((err, phones)=>{ // 	console.log(phones); // }); // Phone.find({}).sort({price : -1}).exec((err, phones)=>{ //  	console.log(phones); // }); Phone.find({}).sort('-price').limit(1).exec((err, phones) => { 	console.log('---findTheMostExpensivePhone()---------------------------------'); 	if (err) { 		console.log(err); 	} else { 		console.log(phone); 	} });       // Query.sort('price')    // Query.sort({price : 'asc'}})    // Query.sort({price : 'ascending'}})    // Query.sort({price : 1}}) // 查询结果按price数值升序排列 // Phone.find({}).sort('price').exec((err, phones)=>{ // 	console.log(phones); // }); // Phone.find({}).sort({price : 'asc'}).exec((err, phones)=>{ // 	console.log(phones); // }); // Phone.find({}).sort({price : 'ascending'}).exec((err, phones)=>{ // 	console.log(phones); // }); // Phone.find({}).sort({price : 1}).exec((err, phones)=>{ //  	console.log(phones); // }); Phone.find({}).sort('price').limit(1).exec((err, phones) => { 	console.log('---findTheMostCheapPhone()---------------------------------');		  	if (err) { 		console.log(err); 	} else { 		console.log(phone); 	} }); 
控制台输出:
下一篇mongoose教程–排重与计数 
About Sodino