mysql - mongo如何对一个collection进行顺序上的调整呢?
怪我咯
怪我咯 2017-04-17 14:50:57
0
3
591

如题目所说,我这里在mongo中有一个collection,需要往里面插入一些数据,但是我想把插入的这几个数据在这个collection的前几位显示,大家有什么好的办法没?在此先谢过了

怪我咯
怪我咯

走同样的路,发现不同的人生

reply all(3)
洪涛

The natural order in a collection is managed by mongodb itself and you have no control over it. If you need the data in a certain order, just tell mongodb directly what order it should be in.

伊谢尔伦

Use the sorting function of mongodb. You can take a field that can be used for sorting on the data you insert
Arrange in ascending or descending order, 1 is ascending, -1 is descending

db.coll.find({}).sort({'字段': 1})
伊谢尔伦

It’s a pity that what you want to do cannot be achieved. It can be seen from the JSON specification

An object is an unordered set of name/value pairs.

The collection is unordered, so there is no way to control the position of the elements when displayed.
But think about it from another angle, such a function actually doesn’t mean much to you.

  • If it is in an application, the order you display to the user is the order you define, and has nothing to do with the order in which the elements appear;

  • If it is in the database, only the database administrator can actually see it, and this order is only meaningful to a certain administrator;

In my opinion, this is not a difficult function. The reason why it has not been implemented is because it has no practical value and will only slow down the database. This goes against the values ​​of the database itself: The database The main purpose is to provide you with data efficiently, not to present the data in different forms. Presenting the data should be what the application should care about. If you really want to see certain values, you should control the output elements through projection rather than relying on the original order.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!