[英]Filter Date in MongoDB Arrays
This is the operator Schema on my codes:这是我的代码上的运算符模式:
const operatorSchema = new Schema({
operatorName: {
type: String
},
users:[{
email:String,
payment:Number,
paymentsData: Date,
product: String,
}],
});
I want to filter the user's paymentData date by month within a specific operator.我想在特定运营商中按月过滤用户的 paymentData 日期。
Date keep this format in DB: 2022-07-26T10:45:34.296+00:00
日期在 DB 中保持这种格式:
2022-07-26T10:45:34.296+00:00
I'm trying like this:我正在尝试这样:
async function getUserNumberAndPaymentsbyMonth(operatorName, month){
// const operator = await Operators.findOne({operatorName});
// var myDate = Date.now()
Operators.find( { $and: [ { operatorName: operatorName }, { paymentsData: { $gte: new Date(2022, 7, 21),$lt: new Date(2022, 7, 25) }} ] },function (err, docs) { // Operators.find({operatorName: operatorName, paymentsData: {$gte: Date(2022,7,21)}}, function (err, docs) {
if (err) console.log(err)
else {
docs.forEach(function(data){
console.log(data)
})
// res.render('total_earns_operator_tables', { operators: docs });
}
});
}
But I get all dates not between (2022, 7, 21) and (2022, 7, 25) in related operatorName.但是我在相关的 operatorName 中得到了所有不在 (2022, 7, 21) 和 (2022, 7, 25) 之间的日期。
paymentsData in users array so also I try with this but I get errors when I use like this:用户数组中的支付数据,所以我也尝试使用这个,但是当我像这样使用时出现错误:
Operators.find( { $and: [ { operatorName: operatorName }, {users: { paymentsData: { $gte: new Date(2022, 7, 21),$lt: new Date(2022, 7, 25) }}} ] },function (err, docs) { // Operators.find({operatorName: operatorName, paymentsData: {$gte: Date(2022,7,21)}}, function (err, docs) {
if (err) console.log(err)
else {
docs.forEach(function(data){
console.log(data)
})
// res.render('total_earns_operator_tables', { operators: docs });
}
});
How can I do this?我怎样才能做到这一点?
EDIT编辑
I try with this according to suggestion but it returns anything:我根据建议尝试了这个,但它返回任何东西:
Operators.aggregate([
{ $match: { operatorName: operatorName}},
{ $unwind: '$users'},
{ $match: {'users.paymentsData':
{ $gte: new Date(2022, 7, 21),$lt: new Date(2022, 7, 25) }
}
}]
,function (err, docs) { // Operators.find({operatorName: operatorName, paymentsData: {$gte: Date(2022,7,21)}}, function (err, docs) {
if (err) console.log(err)
else {
docs.forEach(function(data){
console.log(data)
})
// res.render('total_earns_operator_tables', { operators: docs });
}
});
You can use an aggregate function like this,您可以像这样使用聚合 function,
Operators.aggregate(
{ $match: { operatorName: operatorName)}},
{ $unwind: '$users'},
{ $match: {'users.paymentsData': {
{ $gte: new Date(2022, 7, 21),$lt: new Date(2022, 7, 25) }
}
}
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.