简体   繁体   English

MongoDB找到集合中的最新日期

[英]MongoDB find newest date in collection

I want to search the newest date in a collection. 我想搜索集合中的最新日期。 The date is formatted like this: YYYY-MM-DD . 日期的格式如下: YYYY-MM-DD For instance: 例如:

{ "release" : "2014-09-25", "desc" : "Test1", "status" : "ok", "_id" : "…" }
{ "release" : "2014-09-26", "desc" : "Test2", "status" : "ok", "_id" : "…" }
{ "release" : "2014-09-27", "desc" : "Test3", "status" : "ok", "_id" : "…" }

The result set should be: 结果集应为:

{ "release" : "2014-09-27", "desc" : "Test3", "status" : "ok", "_id" : "…" }

Is there a special mongoDB operator for that case, or do I have to fetch all documents in the collection and make a loop? 在这种情况下是否有特殊的mongoDB运算符,还是我必须获取集合中的所有文档并进行循环?

Any help would be greatly appreciated 任何帮助将不胜感激

You are storing date as String, please change it to date object and the you could sort it using mongo sort 您将日期存储为String,请将其更改为date对象,您可以使用mongo sort对其进行排序

http://docs.mongodb.org/manual/reference/method/cursor.sort/ http://docs.mongodb.org/manual/reference/method/cursor.sort/

db.collection.find().sort( { date: -1 } ).limit(1)

For storing as date from moment.js see this link here: Inserting a momentjs object in Meteor Collection 要存储moment.js中的日期,请参见此处的链接: 在Meteor Collection中插入momentjs对象

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM