MongoDB 日期排序的粒度?
是否可以对 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你的问题的简短答案是“否”。如果不存储另一个字段,这是不可能的。即使在 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.