mongodb插入的最后一个文档

WBOY
Release: 2016-06-06 20:20:17
Original
1011 people have browsed it

我们在使用Mongodb时,有一个需求,就是要取得某个集合的最后一条记录.
最开始的开始我们想通过_id排序, 但是这个应该不是严格的顺序.
我们还尝试了时间戳的方式,这个也不能解决我们的问题.
最后没办法我们就借助,redis生成了自增的id,存入的mongodb中.
不过这个用法真的很恶心.大家有什么好的方法解决这个问题吗?

回复内容:

我们在使用Mongodb时,有一个需求,就是要取得某个集合的最后一条记录.
最开始的开始我们想通过_id排序, 但是这个应该不是严格的顺序.
我们还尝试了时间戳的方式,这个也不能解决我们的问题.
最后没办法我们就借助,redis生成了自增的id,存入的mongodb中.
不过这个用法真的很恶心.大家有什么好的方法解决这个问题吗?

_id排就可以了,这个得生成本身就跟时间有关系

ObjectId is a 12-byte BSON type, constructed using:

a 4-byte value representing the seconds since the Unix epoch,
a 3-byte machine identifier,
a 2-byte process id, and
a 3-byte counter, starting with a random value

如果没有自己复写_id的算法,可以用_id直接排序的

除非你们自己生产了Mongodb的ObjectId,否则_id是绝对唯一的primary key. 通过下面的排序就可以轻易得到最后一条数据.

 $sort:{_id:-1 }
Copy after login
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact [email protected]
Popular Tutorials
More>
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!