admin管理员组文章数量:1397710
I have a collection that contains documents with a date attribute like so:
{
title: "whatever",
created: ISODate("2013-05-27T03:36:50Z")
}
I would like to select records that were created on a certain day. I was hoping I could use toDateString()
and pare the values but when I do a search like the one below:
db.myCollection.find({ 'created.toDateString()': new Date('05/27/2013').toDateString() }).pretty()
But this does not work. Is there any way to do what I am attempting above?
I have a collection that contains documents with a date attribute like so:
{
title: "whatever",
created: ISODate("2013-05-27T03:36:50Z")
}
I would like to select records that were created on a certain day. I was hoping I could use toDateString()
and pare the values but when I do a search like the one below:
db.myCollection.find({ 'created.toDateString()': new Date('05/27/2013').toDateString() }).pretty()
But this does not work. Is there any way to do what I am attempting above?
Share Improve this question edited Jun 26, 2017 at 11:32 Neil Lunn 151k36 gold badges355 silver badges325 bronze badges asked Mar 20, 2014 at 22:48 Abe MiesslerAbe Miessler 85.2k104 gold badges321 silver badges495 bronze badges1 Answer
Reset to default 3If you want to select records then use a date range:
db.collection.find({
created: { "$gte": new Date("2013-05-27"), "$lt": new Date("2013-05-28") }
})
And that selects all the contained hours, minutes etc, falling between the two dates.
So you should be trying to use the date values and not coerce into strings.
If you want this for doing aggregation or otherwise need the results in a day only format then do this using $project and the date operators:
db.collection.aggregate([
// Still match on the normal date forms, this time whole month
{ "$match": {
created: {
"$gte": new Date("2013-05-01"),
"$lt": new Date("2013-05-31")
}
}},
// Project the date
{ "$project": {
"date": {
"year" : { "$year" : "$created" },
"month" : { "$month" : "$created" },
"day": : { "$dayOfMonth": "$created" }
},
"title": 1
}},
// Group on day and title
{ "$group": {
"_id": {
"date" : "$date",
"title" : "$title"
},
"count": { "$sum": 1 }
}},
// Sort by date
{ "$sort": {
"_id.date.year": 1,
"_id.date.month": 1,
"_id.date.day": 1,
}},
// Project nicer dates and document
{ "$project": {
"_id": 0,
"date": { "$concat": [
{ "$substr": [ "$_id.date.year", 0, 4 ] },
"-",
{ "$substr": [ "$_id.date.month", 0, 2 ] },
"-",
{ "$substr": [ "$_id.date.day", 0, 2 ] }
]},
"title": "$_id.title",
"count": 1
}}
])
本文标签: javascriptPossible to compare date strings in mongodbStack Overflow
版权声明:本文标题:javascript - Possible to compare date strings in mongodb? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744124604a2591898.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论