Mongodb 按日期排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36441661/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Mongodb sort by date
提问by Joey
I have a document with a field _id
has type ObjectId
, and a field created_at
has type Date
.
我有一个文档,其中一个字段_id
有 type ObjectId
,一个字段created_at
有 type Date
。
_id
is of course increasing, and the value of created_at
is current_date should be increasing.
_id
当然是在增加,并且created_at
is current_date的值应该在增加。
So my question is :
所以我的问题是:
- Is there any chance that 2 documents, A and B,
A._id > B._id
, butA.created_at < B.created_at
. - How to keep
created_at
as precise as possible, so the order ofcreated_at
corresponds to_id
.
- 有没有可能 2 个文件,A 和 B
A._id > B._id
,,但是A.created_at < B.created_at
. - 如何保持
created_at
尽可能精确,所以 的顺序created_at
对应于_id
.
回答by Sukanta
you can use order_by on documents collection like
您可以在文档集合上使用 order_by,例如
in Rails
在 Rails 中
Product.order_by("created_at desc")
in Mongodbfor example
以 Mongodb为例
db.products.find().sort({"created_at": 1}) --- 1 for asc and -1 for desc