您的位置:首页 > Web前端 > Node.js

【Node.js】mongoose教程06--排序

2016-06-05 17:05 429 查看
Sodino
本文的查询是指存储了5个手机数据后再查询。存储实现见文章:【Node.js】mongoose教程—存储。GitHub源码链接:sodino#MongoDemo排序文档链接
12345678910111213141516171819
Query#sort(arg)    Sets the sort orderParameters:    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. Thesort 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" descendingquery.sort({ field: 'asc', test: -1 });  // equivalentquery.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。
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
// 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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: