I am learning Mongodb aggregate function and I'm working on a query. My document looks like below.
[
{
"_id": 17,
"members": [{
"email": "[email protected]",
"status": "pending",
"joined": ISODate("2020-05-20T02:04:00Z")
},
{
"email": "[email protected]",
"status": "pending",
"joined": ISODate("2020-05-20T02:36:00Z")
}
],
"messages": [{
"c": "m1",
"ts": ISODate("2020-05-20T02:04:15Z")
},
{
"c": "m2",
"ts": ISODate("2020-05-20T02:36:31Z")
}
]
}
]
Each document has 2 arrays: members and messages. I need to filter to one element in members (using email) and filter messages based on "members.joined" property matched against "messages.ts" property.
I tried different ways, couldn't achieve it yet. In the below query, I have hardcoded date ISODate("2020-05-20T02:36:00Z") instead of using members.joined property. How can I write an optimized query to achieve the same?
db.coll.aggregate([
{
$match: {
_id: 17,
"members.email": "[email protected]"
}
},
{
$project: {
messages: {
$filter: {
input: "$messages",
as: "messs",
cond: {
$gte: [
"$$messs.ts",
ISODate("2020-05-20T02:36:00Z") // supposed to have members.$.joined property here
]
}
}
}
}
}
])
The expected result is the second element from messages that should be printed.
ISODate("2020-05-20T02:04:15Z")isn't itISODate("2020-05-20T02:36:00Z")taken from object where"email": "[email protected]"? Also do you want to filtermembersarray as well to keep only object where"email": "[email protected]"- do you need it or members array needs to be as is original ? Can you edit question with required o/p from given sample doc..