mongodb 从集合数组对象字段中获取所有唯一值

chhkpiq4  于 2023-06-22  发布在  Go
关注(0)|答案(2)|浏览(101)

我有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()函数存在,但我想看看它是如何处理数组中的对象字段的。

qvk1mo1f

qvk1mo1f1#

  1. $group-对所有文档进行分组,并将members.user_id数组添加到user_ids数组中。这导致user_ids成为嵌套数组。
  2. $set-设置user_ids字段。
    2.1. $setUnion-联合结果 2.1.1 中的元素。这导致元素是不同的。
    2.1.1. $reduce-展平嵌套数组user_ids
db.collection.aggregate([
  {
    $group: {
      _id: null,
      user_ids: {
        $addToSet: "$members.user_id"
      }
    }
  },
  {
    $set: {
      user_ids: {
        $setUnion: {
          $reduce: {
            input: "$user_ids",
            initialValue: [],
            in: {
              $concatArrays: [
                "$$value",
                "$$this"
              ]
            }
          }
        }
      }
    }
  }
])

Demo @ Mongo Playground

fdbelqdn

fdbelqdn2#

/*
  Expected Output:
  [
    {
      members: ['11', '23', '73', '59', '37', '28'],
    },
  ]

  step 1: unwind members
  step 2: group by null and add to set members.user_id
  step 3: project members
  
*/

db.collection.aggregate([
  {
    $unwind: '$members',
  },
  {
    $group: {
      _id: null,
      members: {
        $addToSet: '$members.user_id',
      },
    },
  },
  {
    $project: {
      _id: 0,
      members: 1,
    },
  },
]);

相关问题