MongoDB 日期排序的粒度?

发布于 2024-10-07 19:55:04 字数 93 浏览 8 评论 0原文

是否可以对 MongoDB 的日期值进行粒度排序?

我想按日期对结果进行排序,但我不关心小时/分钟/秒数据。我不想存储像“20101215”这样的附加参数。

Is it possible to sort MongoDB's date values with a granularity?

I'd like to order my results by date, but I don't care about the hour/minute/second data. I'd prefer not to have to store an additional parameter like '20101215'.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

反差帅 2024-10-14 19:55:04

你的问题的简短答案是“否”。如果不存储另一个字段,这是不可能的。即使在 Mongo 中排序时您可能不想 b/c,您也确实需要对要排序的字段建立索引,否则数据库将需要扫描数据库中的每个文档来进行排序。因此,如果您要按照您的建议进行操作,您还需要对部分日期字段建立索引,这在 mongo 中也是不可能的。

我认为最好的方法是存储 2 个字段,一个用于年/月/日,另一个用于小时/分钟/秒。然后您将在排序和索引方面拥有更大的灵活性。它并不像您希望的那样干净或理想,但这是数据库的唯一选择。

另一种选择是在结果返回后优化应用程序中的顺序。

The short answer to your question is "No". It's not possible without storing another field. Even if it were possible you wouldn't want to b/c when sorting in Mongo you really need to index the fields you are sorting by, otherwise the db will need to scan every document in the db to do the sort. So if you were to do what you are suggesting you would also need to index on the partial date field which is also not possible in mongo.

I think the best approach would be to store 2 fields, one for the year/month/day and another for the hour/min/secs. Then you'll have more flexibility with sorting and indexing. It's not as clean or ideal as you'd probably like, but that's the only option with the db.

The other option would be to refine the order in your application after the results come back.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文