I have the collection sessions
:
[
{
"_id": "",
"members": [
{ "user_id": "11", "joined_at": "2023-06-15T04:50:06.298Z" },
{ "user_id": "23", "joined_at": "2023-06-15T04:50:06.298Z" },
{ "user_id": "73", "joined_at": "2023-06-15T04:50:06.298Z" }
]
},
{
"_id": "",
"members": [
{ "user_id": "59", "joined_at": "2023-06-15T04:50:06.298Z" },
{ "user_id": "37", "joined_at": "2023-06-15T04:50:06.298Z" },
{ "user_id": "11", "joined_at": "2023-06-15T04:50:06.298Z" }
]
},
{
"_id": "",
"members": [
{ "user_id": "11", "joined_at": "2023-06-15T04:50:06.298Z" },
{ "user_id": "23", "joined_at": "2023-06-15T04:50:06.298Z" },
{ "user_id": "28", "joined_at": "2023-06-15T04:50:06.298Z" }
]
}
]
I want to get all distinct user_id
values from the entire collection (or based on a filter). Based on the documents above, the intended results should be:
["11", "23", "73", "59", "37", "28"]
I know that the collection.distinct() function exists, but I’d like to see how it’s done for objects fields in an array.
2
Answers
$group
– Group all documents and add themembers.user_id
array into theuser_ids
array. This results in theuser_ids
being a nested array.$set
– Setuser_ids
field.2.1.
$setUnion
– Union the elements from the result 2.1.1. This results in the elements are distinct.2.1.1.
$reduce
– Flatten the nested arrayuser_ids
.Demo @ Mongo Playground