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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 20:42:28  来源:igfitidea点击:

Mongodb sort by date

mongodb

提问by Joey

I have a document with a field _idhas type ObjectId, and a field created_athas type Date.

我有一个文档,其中一个字段_id有 type ObjectId,一个字段created_at有 type Date

_idis of course increasing, and the value of created_atis current_date should be increasing.

_id当然是在增加,并且created_atis current_date的值应该在增加。

So my question is :

所以我的问题是:

  1. Is there any chance that 2 documents, A and B, A._id > B._id, but A.created_at < B.created_at.
  2. How to keep created_atas precise as possible, so the order of created_atcorresponds to _id.
  1. 有没有可能 2 个文件,A 和 B A._id > B._id,,但是A.created_at < B.created_at.
  2. 如何保持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