mongodb在robo3T下查询正常,语句如下:
`db.getCollection('paimings').aggregate([
{
$match: {
date: {
$gte: ISODate('2020-04-25 23:50:00'),
$lte: ISODate('2020-04-25 24:00:00'),
}
},
},
{ $unwind: '$paiming' },
{ $group: { _id: '$paiming', cishu: { $sum: 1 } } },
{ $project: { _id: 0, keyword: '$_id', cishu: 1 } },
{ $sort: { cishu: -1 } },
])`
在nodejs里查询不出来,语句如下:
router.get('/keycount', (req, res) => {
PaiMing.aggregate([
{
$match: {
date: {
$gte: new Date(tools.dateAdd8(req.query.begin)).toISOString(),
$lte: new Date(tools.dateAdd8(req.query.end)).toISOString(),
}
},
},
{ $unwind: '$paiming' },
{ $group: { _id: '$paiming', cishu: { $sum: 1 } } },
{ $project: { _id: 0, keyword: '$_id', cishu: 1 } },
{ $sort: { cishu: -1 } },
])
.then((paiming) => {
res.status(200).send(paiming)
})
.catch((err) => {
console.log()
})
})
日期换成如下也不行
date: {
$gte: new Date('2020-04-25 23:50:00').toISOString(),
$lte: new Date('2020-04-25 24:00:00').toISOString(),
}
如果不加日期范围查询正常:
router.get('/keycount', (req, res) => {
PaiMing.aggregate([
{
$match: {
keyword:
req.query.select === '0'
? new RegExp(req.query.keyword)
: req.query.keyword
},
},
{ $unwind: '$paiming' },
{ $group: { _id: '$paiming', cishu: { $sum: 1 } } },
{ $project: { _id: 0, keyword: '$_id', cishu: 1 } },
{ $sort: { cishu: -1 } },
])
.then((paiming) => {
res.status(200).send(paiming)
})
.catch((err) => {
console.log()
})
})
困扰我好几天了,高手帮忙。
那是因为你在数据库中用了Date类型来存储日期,但是在nodejs查询时候用了string去匹配,必须查询时候也用Date类型才能查出来