我为用户存储的数据采用以下格式:
{
name: 'XYZ',
email: 'abc@gmail.com',
password: 'encrypted',
categories: [
{
name: 'category1',
type: 'type1',
},
{
name: 'category2',
type: 'type2',
}
],
transactions: [
{
date: 2020-04-09T06:00:30.000Z,
type: 'type1',
category: 'category1',
description: 'some desc',
},
{
date: 2020-04-08T06:00:30.000Z,
type: 'type2',
category: 'category1',
description: 'some desc',
},
{
date: 2020-04-07T06:00:30.000Z,
type: 'type3',
category: 'category1',
description: 'some desc',
}
]
}
我想在提供唯一的电子邮件后获取特定用户的数据,但同时我希望在2个日期之间过滤交易。
示例我想要具有email = abc@gmail.com
的用户数据和dates between 2020-04-08 and 2020-04-09
的交易数据。
示例输出如下:
{
name: 'XYZ',
email: 'abc@gmail.com',
categories: [...],
transactions: [
{
date: 2020-04-09T06:00:30.000Z,
type: 'type1',
category: 'category1',
description: 'some desc',
},
{
date: 2020-04-08T06:00:30.000Z,
type: 'type2',
category: 'category1',
description: 'some desc',
}]
}
或者只对给定用户电子邮件的给定日期之间的交易也可以。
尝试使用此查询
User.aggregate([
{$match: {email: email}},
{$unwind: '$transactions'},
{$match: {'transactions.date': {$gt: startDate, $lt: endDate}}},
{
$group: {
_id: '$_id',
transactions: {
$type: "$transactions.type",
$category: "$transactions.category",
$date: "$transactions.date",
$description: "$transactions.decription"
}
}
}
]).exec((err, data) => {
if (err) throw err;
console.log(data);
})
按照以下说明获取错误The field 'transactions' must specify one accumulator