我试图根据一些匹配条件获取数据.首先我试过这个:
这里ending_date是完整日期格式
这里ending_date是完整日期格式
Offer.aggregate([ { $match: { carer_id : req.params.carer_id,status : 3 } },{ $group : { _id : { year: { $year : "$ending_date" },month: { $month : "$ending_date" }},count : { $sum : 1 } } }],function (err,res) { if (err) ; // Todo handle error console.log(res); });
这给了我以下输出:
[ { _id: { year: 2015,month: 11 },count: 2 } ]
现在我想检查一年,所以我正在尝试这个:
Offer.aggregate([ { $project: { myyear: {$year: "$ending_date"} } },{ $match: { carer_id : req.params.carer_id,status : 3,$myyear : "2015" } },res) { if (err) ; // Todo handle error console.log(res); });
这给了我以下输出:
[]
正如你所看到的,_id有2015年作为一年,所以当我匹配年份它应该是阵列.但我得到空数组.为什么这个?
有没有其他方法只匹配年份整个日期时间?
这是样本数据
{ "_id": { "$oid": "56348e7938b1ab3c382d3363" },"carer_id": "55e6f647f081105c299bb45d","user_id": "55f000a2878075c416ff9879","starting_date": { "$date": "2015-10-15T05:41:00.000Z" },"ending_date": { "$date": "2015-11-19T10:03:00.000Z" },"amount": "850","total_days": "25","status": 3,"is_confirm": false,"__v": 0 } { "_id": { "$oid": "563b5747d6e0a50300a1059a" },"starting_date": { "$date": "2015-11-06T04:40:00.000Z" },"ending_date": { "$date": "2015-11-16T04:40:00.000Z" },"amount": "25","total_days": "10","__v": 0 }
解决方法
您忘记在$match和$group中预测您正在使用的字段.要快速修复,请改用此查询:
Offer.aggregate([ { $project: { myyear: { $year: "$ending_date" },carer_id: 1,status: 1,ending_date: 1 } },{ $match: { carer_id: req.params.carer_id,myyear: 2015,status: 3 } },{ $group: { _id: { year: { $year: "$ending_date" },month: { $month: "$ending_date" } },count: { $sum: 1 } } }],res) { if (err) {} // Todo handle error console.log(res); });
也就是说,Blakes Seven解释了如何在她的回答中做出更好的询问.我认为你应该尝试使用她的方法.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。