The documents follow this structure:
{
"_id" : ObjectId("5a01b474d88dc4001e684c97"),
"created_time" : ISODate("2017-11-07T11:26:12.563+0000"),
"posts" : [
{
"story" : "Test",
"created_time" : ISODate("2017-11-06T17:38:02.000+0000"),
"id" : "769055806629274_768721009996087",
"_id" : ObjectId("5a01b498d88dc4001e68553c")
},
{
"story" : "Test",
"created_time" : ISODate("2017-11-05T12:00:00.000+0000"),
"id" : "1637086293239159_2011737915773993",
"_id" : ObjectId("5a01b498d88dc4001e68553d")
}
[...]
]
}
I want to filter the posts collection by created_time
. Each post needs to have created_time
greater than created_time
of the document. In other words, I want to get posts only for the last month based on the document.
I'm trying this aggregation:
db.collection.aggregate([
{
$project: {
"past_month": {
$subtract: ["$created_time", 2629746000] //a month
},
"created_time": "$created_time",
"posts": "$posts"
}
}, {
$unwind: '$posts'
}, {
$match: {
"posts.created_time": {
$gte: "$past_month"
}
}
}, {
"$group": {
"_id": "$_id",
"posts": {
"$push": "$posts"
}
}
}
])
But the result is always empty. If I change $gte: "$past_month"
to $gte: ISODate("2017-10-08T00:57:06.563+0000")
to test, the results is not empty.