I would like to print the expected results below with the MongoDB command for the document to be processed.
(Some documents do not contain some arrays)
{
"_id"—ObjectId ("60ddc26b03edfb7a6b424f10"),
"member": [
{
"joinDate": "2021-07-01 12:00:00.000",
"username": "John"
},
{
"joinDate": "2021-07-01 13:00:00.000",
"username": "Maria"
}
],
"createdAt": "2021-07-01 11:00",
"roomName": "roomA",
}
{
"_id"—ObjectId("60ddbcccd495870939756dcb"),
"member": [
{
"joinDate": "2021-07-01 14:00:00.000",
"userName": "Jack"
},
{
"joinDate": "2021-07-01 11:00:00.000",
"userName": "George"
}
],
"createdAt": "2021-07-01 10:00",
"roomName": "roomB"
}
{
"_id"—ObjectId("60ddbcccd495870939756dcc"),
"createdAt": "2021-07-01 12:00",
"roomName": "roomC"
}
Output results that meet the following conditions
{
"_id"—ObjectId("60ddbcccd495870939756dcb"),
"latestJoinDate": "2021-07-01 14:00:00.000",
"latestUserName": "Jack",
"createdAt": "2021-07-01 10:00",
"roomName": "roomB"
}
{
"_id"—ObjectId ("60ddc26b03edfb7a6b424f10"),
"latestJoinDate": "2021-07-01 13:00:00.000",
"latestUserName": "Maria",
"createdAt": "2021-07-01 11:00",
"roomName": "roomA",
}
I solved myself!
Below is the query I was looking for.
db.collection.aggregate([
{
$match: {
member: {
$exists —true
}
}
},
{
$addFields: {
member: {
$arrayElemAt: [
"$member",
{
$indexOfArray: [
"$member.joinDate",
{
$max: "$member.joinDate"
}
]
}
]
}
}
},
{
$project: {
createdAt: 1,
roomName: 1,
latestJoinDate: "$member.joinDate",
latestUserName: "$member.userName"
}
},
{
$sort: {
latestJoinDate: -1
}
}
])
https://mongoplayground.net/p/mYE2Q1tk4ij
© 2024 OneMinuteCode. All rights reserved.