从集合中返回今天文档的最有效方法
The most efficient way to returning today's documents from a collection
我有一个集合,其中该集合中的所有文档都有一个日期时间戳,其中包括时间和日期。
使用聚合框架时,我怎么说给我今天的值?以下只给我午夜的条目。
db.strategy.aggregate(
[
{
$match: {
"date": new Date()
}
},
]
);
要获取具有今天日期时间值的文档,您需要创建一个日期查询范围,其中 start
日期对象应将当前日期时间保持在 00:00:00.000
(毫秒精度)并将今天日期的小时数设置为 23:59:59.999
到 end
日期变量。
例如:
// Create the start date which holds the beginning of today
var todayStart = new Date();
todayStart.setHours(0,0,0,0);
// Create the end date which holds the end of today
var todayEnd = new Date();
todayEnd.setHours(23,59,59,999);
// Create the date range query object
var query = {
"date": {
$gte: todayStart,
$lte: todayEnd
}
};
// using the find() method
db.strategy.find(query);
或使用aggregate()
方法作为
db.strategy.aggregate({ "$match": query });
您应该得到范围内的值,即从今天的 12AM 时间戳到今天的 23:59:59 时间戳。
Var d = new Date();
var 开始日期 = d.setHours(0,0,0);
var endDate = d.setHours(23,59, 59);
db.strategy.aggregate(
[
{
$匹配:{
"date": {$gte: 开始日期, $lte: 结束日期}
}
},
]
);
我有一个集合,其中该集合中的所有文档都有一个日期时间戳,其中包括时间和日期。
使用聚合框架时,我怎么说给我今天的值?以下只给我午夜的条目。
db.strategy.aggregate(
[
{
$match: {
"date": new Date()
}
},
]
);
要获取具有今天日期时间值的文档,您需要创建一个日期查询范围,其中 start
日期对象应将当前日期时间保持在 00:00:00.000
(毫秒精度)并将今天日期的小时数设置为 23:59:59.999
到 end
日期变量。
例如:
// Create the start date which holds the beginning of today
var todayStart = new Date();
todayStart.setHours(0,0,0,0);
// Create the end date which holds the end of today
var todayEnd = new Date();
todayEnd.setHours(23,59,59,999);
// Create the date range query object
var query = {
"date": {
$gte: todayStart,
$lte: todayEnd
}
};
// using the find() method
db.strategy.find(query);
或使用aggregate()
方法作为
db.strategy.aggregate({ "$match": query });
您应该得到范围内的值,即从今天的 12AM 时间戳到今天的 23:59:59 时间戳。
Var d = new Date(); var 开始日期 = d.setHours(0,0,0); var endDate = d.setHours(23,59, 59); db.strategy.aggregate( [ { $匹配:{ "date": {$gte: 开始日期, $lte: 结束日期} } },
]
);