MongoDB指南针:选择不同的字段值

时间:2019-11-01 02:49:22

标签: mongodb mongodb-compass

我使用的是MongoDB Compass,没有mongo Shell。我需要使用mongoDB Compass工具构建查询,以从集合中选择“体裁”字段的不同值。有人可以帮忙吗?

compass tool screenshot

样本输入:

{"_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"}

预期输出:纪录片,短片

2 个答案:

答案 0 :(得分:1)

您可以使用$unwind$group通过Compass中的聚合框架来执行此操作。执行$ unwind为目标数组中的每个元素创建一个唯一的文档,这使$ group阶段的$addToSet运算符可以将流派捕获为不同的元素。

管道:

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

有关指南针示例,请参见以下屏幕截图:

enter image description here

答案 1 :(得分:0)

谢谢克里斯蒂安的回答。我根据您的建议制定了以下答案。

我的管道:

[{$project: {
  genres: {$split: ["$genre",", "  ]}

}
}, {$unwind: {
  path: "$genres",
  includeArrayIndex: 'string',
  preserveNullAndEmptyArrays: true

  }}, {$group: {
  _id: null,
  unique_genres: {
    $addToSet: '$genres'
  }
}}]

compass agregation screenshot