我有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" }
]
}
]
我想从整个集合(或基于过滤器)中获取所有不同的user_id
值。根据上述文件,预期结果应为:
["11", "23", "73", "59", "37", "28"]
我知道collection.distinct()函数存在,但我想看看它是如何处理数组中的对象字段的。
2条答案
按热度按时间qvk1mo1f1#
$group
-对所有文档进行分组,并将members.user_id
数组添加到user_ids
数组中。这导致user_ids
成为嵌套数组。$set
-设置user_ids
字段。2.1.
$setUnion
-联合结果 2.1.1 中的元素。这导致元素是不同的。2.1.1.
$reduce
-展平嵌套数组user_ids
。Demo @ Mongo Playground
fdbelqdn2#