我的mongoDB集合中有如下数据。我想今天计算总数或search_term。
_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"
我尝试了以下查询。我用了片刻。我不是我犯的错。
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)
});
答案 0 :(得分:2)
您可以在mongodb 3.6
中尝试以下查询db.collection.find({
"$expr": {
"$gte": [{ "date": { "$dateFromString": { "dateString": "$date" }}}, start.toDate() ],
"$lt": [{ "date": { "$dateFromString": { "dateString": "$date" }}}, end.toDate() ]
}
}).count()
或聚合
db.collection.aggregate([
{ "$addFields": {
"date": {
"$dateFromString": {
"dateString": "$date"
}
}
}},
{ "$match": { "date": { "$gte": start.toDate(), "$lt": end.toDate() }}},
{ "$count": "count" }
])
答案 1 :(得分:1)
尝试:
history.count({date: {
$gte: start,
$lt: end
}}, function( err, count){
console.log( "Number of users:", count );
})
用于本机mongodb驱动程序
db.collection(collectionName).count({}, function(error, numOfDocs){
if(error) return callback(error);
db.close();
callback(null, numOfDocs);
});
答案 2 :(得分:1)
您可以尝试
db.col.aggregate([{$addFields: {
convertedDate: { $toDate: "$date" }
}},
{"$match" :
{"convertedDate" :
{"$gte" : ISODate("2018-08-23T09:34:32.000Z"),
"$lte" : ISODate("2018-08-23T09:34:32.000Z")}
}
},
{"$group" : {"_id" : null,"count" : {"$sum" : 1}}},
{"$project" : {"_id" : 0}}
])
这是针对Node js的
var start = moment().startOf('day');
var end = moment().endOf('day');
history.aggregate([{
$addFields: {
convertedDate: { $toDate: "$date" }
}
},
{
"$match":
{
"convertedDate":
{
"$gte": start,
"$lte": end
}
}
},
{ "$group": { "_id": null, "count": { "$sum": 1 } } },
{ "$project": { "_id": 0 } }
], function (err, count) {
console.log(count)
})
答案 3 :(得分:0)
您正在存储日期的字符串表示形式。在存储到数据库中之前,先对矩对象调用toDate()