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
4.4k views
in Technique[技术] by (71.8m points)

mongodb排序问题?

mongodb针对字段值一样是怎样排序的,需要查找某个字段并且按照id来排序,数据:

[
{_id:1,status:"A"},
{_id:2,status:"A"},
{_id:3,status:"C"},
{_id:4,status:"A"},
{_id:5,status:"A"},
{_id:6,status:"B"},
{_id:7,status:"B"},
{_id:8,status:"A"},
...
]

直接用_id排序:

db.list.find({status:"A"}).sort({_id:-1}).limite(10)

达到效果,但扫描量大.


在status上创建索引(正向),查询:

db.list.find({status:"A"}).sort({status:-1}).limite(10)

达到效果,发现和_id排序一致,但是这种排序无法比较,字段都是"A",结果是怎样来的,是根据_id的还是mongodb默认的排序,更新,删除,创建新的数据好像都不影响排序.

所以能不能使用上面的方法排序,还是需要创建一个复合索引{status:1,_id:1}.


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

1 Reply

0 votes
by (71.8m points)

扫描量大是怎么回事?

db.list.find({status:"A"}).sort({_id:-1}).limite(10)

你就给status加个索引,然后用这个查询不行吗


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

...