23

我正在使用 MongoDB Compass 并且没有 Mongo Shell。我需要使用 MongoDB Compass 工具构建一个查询,以从我的集合中选择“流派”字段的不同值。

指南针工具截图

样本输入:

{"_id":{"$oid":"58c59c6a99d4ee0af9e0c34e"},"title":"Bateau-mouche sur la Seine","year":{"$numberInt":"1896"},"imdbId":"tt0000042","genre":["Documentary”,”Short”],"viewerRating":{"$numberDouble":"3.8"},"viewerVotes":{"$numberInt":"17"},"director":"Georges Mlis"}
{"_id":{"$oid":"58c59c6a99d4ee0af9e0c340"},"title":"Watering the Flowers","year":{"$numberInt":"1896"},"imdbId":"tt0000035","genre":["Short”],"viewerRating":{"$numberDouble":"5.3"},"viewerVotes":{"$numberInt":"33"},"director":"Georges M�li�s"}
{"_id":{"$oid":"58c59c6a99d4ee0af9e0c34a"},"title":"The Boxing Kangaroo","year":{"$numberInt":"1896"},"imdbId":"tt0000048","genre":["Short”],"viewerRating":{"$numberDouble":"5.2"},"viewerVotes":{"$numberInt":"48"},"director":"Birt Acres"}

预期输出:纪录片,短片

4

1 回答 1

58

您可以通过 Compass 中的聚合框架使用$unwind$group来做到这一点。执行 $unwind 是为了为目标数组中的每个元素创建一个唯一的文档,这使得 $group 阶段中的$addToSet运算符能够将类型捕获为不同的元素。

管道:

[
  {
    $unwind: {
      path: '$genre',
      preserveNullAndEmptyArrays: true
    }
  },
  {
    $group: {
      _id: null,
      uniqueGenres: { $addToSet: '$genre' }
    }
  }
]

指南针示例见下面的截图:

在此处输入图像描述

于 2019-11-04T03:11:43.943 回答