有没有一种方法可以有效地找到 MongoDB 中某个字段的所有唯一值?

Is there a way to efficiently find all unique values for a field in MongoDB?

考虑一组用户:

{ name: 'Jeff' }
{ name: 'Joel' }

有没有办法有效地获取 name 的所有唯一值?

User.pluck(:name).uniq

到return

[ 'Jeff', 'Joel' ]

我认为这会得到整个集合,因此效率很低。

但是,如果name上有一个索引,有没有办法在不获取所有文档的情况下获取所有唯一值?

或者是否有其他方法可以有效地获得唯一性 names

如评论中所述,您可以使用 distinct.

有效地获取集合中所有文档的字段的唯一值

文档特别提到尽可能使用索引,并且它们可以覆盖不同的查询。这意味着只需要将支持索引加载到内存中即可获得结果。

When possible, db.collection.distinct() operations can use indexes.

Indexes can also cover db.collection.distinct() operations. See Covered Query for more information on queries covered by indexes.

在 Ruby 中,您将执行不同的查询:

User.distinct(:name)