I wonder if it it possible to group documents based on a common field and a condition.
In the following collection:
[
{
"pid": "102",
"e_date": ISODate("2017-04-01T00:00:00.000+00:00"),
"h_val": 4,
},
{
"pid": "102",
"e_date": ISODate("2005-04-01T00:00:00.000+00:00"),
"h_val": 5,
},
{
"pid": "102",
"e_date_1": ISODate("2017-05-01T00:00:00.000+00:00"),
"s_val": 87,
"d_val": 58
},
{
"pid": "102",
"e_date_1": ISODate("2016-09-01T00:00:00.000+00:00"),
"s_val": 81,
"d_val": 62
},
{
"pid": "102",
"e_date_1": ISODate("2010-09-01T00:00:00.000+00:00"),
"s_val": 81,
"d_val": 62
},
{
"pid": "101",
"e_date": ISODate("2016-04-01T00:00:00.000+00:00"),
"h_val": 5,
},
{
"pid": "101",
"e_date_1": ISODate("2011-05-01T00:00:00.000+00:00"),
"s_val": 87,
"d_val": 58
},
]
I am trying to group documents based on pid and check if e_date_1 is within 1 year of e_date. I have tried match and group aggregates:
db.collection.aggregate([
{
"$match": {
$expr: {
$lte: [
{
$abs: {
$dateDiff: {
startDate: "$e_date",
endDate: "$e_date_1",
unit: "year"
}
}
},
1
]
}
}
},
{
"$group": {
"_id": "$pid",
"actions": {
"$push": "$$ROOT"
},
"total": {
"$sum": 1
}
}
}
])
But I get all documents grouped by pid not the ones that are within 1 year.