在 mongodb 中使用字符串日期格式查询 [英] Query with string date format in mongodb
本文介绍了在 mongodb 中使用字符串日期格式查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的 mongoDB 集合中有如下数据.我想统计今天的总数或 search_term.
I have a data like below in my mongoDB collection. I want to count the total number or search_term on today basis.
_id:ObjectId("5b7e1d38981cdc1a7c8bb5fc")
search_term:"Baiyoke Boutique"
date:"August 23rd 2018, 9:34:32 am"
_id:ObjectId("5b7e1fa8fa27fd2754080ad9")
search_term:"Baiyoke Boutique"
date:"August 23rd 2018, 9:44:56 am"
_id:ObjectId("5b7e28314d2d0f388c1596cd")
search_term:"Baiyoke Florting Market"
date:"August 23rd 2018, 10:21:21 am"
我尝试了以下查询.我用过时刻.我不是我做的错.
I have tried following query. I have used moment. I am not what mistake I did.
var start = moment().startOf('day');
var end = moment().endOf('day');
history.find({
date: {
$gte: start,
$lt: end
}
}).count().toArray(
function (e, res) {
if (e) callback(e)
else callback(null, res)
});
推荐答案
你可以在mongodb 3.6及以上尝试以下查询
You can try below queries in mongodb 3.6 and above
db.collection.find({
"$expr": {
"$gte": [{ "$dateFromString": { "dateString": "$date" }}, start.toDate() ],
"$lt": [{ "$dateFromString": { "dateString": "$date" }}, end.toDate() ]
}
}).count()
或聚合
db.collection.aggregate([
{ "$addFields": {
"date": {
"$dateFromString": {
"dateString": "$date"
}
}
}},
{ "$match": { "date": { "$gte": start.toDate(), "$lt": end.toDate() }}},
{ "$count": "count" }
])
这篇关于在 mongodb 中使用字符串日期格式查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文