我想查询mongodb以检索从今天午夜到当前时间的记录,但查询中出现错误,请帮助 样本记录:
{
"myDate" : ISODate("2017-07-17T11:06:17.874Z"),
"_id":"xxxx"
}
,
{
"myDate" : ISODate("2017-07-17T11:06:17.874Z"),
"_id":"yyy"
}
db.runReadCommand(
{
aggregate : 'mycollection',
pipeline : [
{$project : {a:new Date (),myDate:1}},
{$project : {myDate:1,a:1,
b : {$dateFromString : { dateString : {$dateToString:{date : '$a',format: "%Y-%m-%d"}}}}}}
,{$match : {myDate: {$lte : a}}}
],cursor:{batchSize : 10}})
问候 克里斯
答案 0 :(得分:1)
您可以使用moment
库来查找一天的开始时间和当前时间
只需查找查询
db.collection.find({
myDate: {
$gte: moment().startOf("day").toDate(),
$lte: moment().toDate()
}
})
具有聚合
db.runReadCommand(
{
aggregate: "mycollection",
pipeline: [
{ $match: {
myDate: {
$gte: moment().startOf("day").toDate(),
$lte: moment().toDate()
}
}}
]
}
)
答案 1 :(得分:1)
不需要moment
的方法:
var r = [
// These are not today:
{_id:0, ts: new ISODate("2018-07-26T07:00:00.000Z")}
,{_id:1, ts: new ISODate("2018-07-26T22:00:00.000Z")}
// These are today and before now (when I wrote this)
,{_id:2, ts: new ISODate("2018-07-27T00:00:00.000Z")}
,{_id:3, ts: new ISODate("2018-07-27T10:00:00.000Z")}
// These are AFTER now (when I wrote this)
,{_id:4, ts: new ISODate("2018-07-27T20:00:00.000Z")}
,{_id:5, ts: new ISODate("2020-01-01T20:00:00.000Z")} // the future!
];
db.foo.drop();
db.foo.insert(r);
now = new Date();
sod = new Date(now);
// Cheapo way to set time elements to midnight:
sod.setHours(0);
sod.setMinutes(0);
sod.setSeconds(0);
sod.setMilliseconds(0);
print("now: " + now);
print("sod: " + sod);
db.foo.aggregate([
{$match: {$and: [ {ts: {"$gte": sod}}, {ts: {"$lt": now}} ] }}
]);