Mongodb 我如何模仿“a”呢;选择“U id”;用mongoid和ruby?

Mongodb 我如何模仿“a”呢;选择“U id”;用mongoid和ruby?,mongodb,mongoid,Mongodb,Mongoid,目前我正在做以下工作: responses = Response.where(user_id: current_user.uid) qids = [] responses.each { |r| qids << r._id} return qids responses=Response.where(用户id:current\u user.uid) qids=[] 每个{r | qids 那有点惯用 就mongoid而言,mongoid提供的唯一“映射”

目前我正在做以下工作:

    responses = Response.where(user_id: current_user.uid)
    qids = []
    responses.each { |r| qids << r._id}
    return qids
responses=Response.where(用户id:current\u user.uid)
qids=[]
每个{r | qids
那有点惯用

就mongoid而言,mongoid提供的唯一“映射”类型功能是自定义map reduce过滤器。您可以查看

在这种情况下,编写这样的筛选器对您没有好处。您正在加载整个数据集(延迟加载没有帮助),并且没有减少任何内容。

使用
.only()
检索更少的数据

quids = Response.only(:_id).where(user_id: current_user.uid).map(&:_id)
直截了当地说这个问题有更好的解决办法 如果您想要获得id或结果集中唯一的东西,那么使用distinct方法在功能上是等效的。这样您可以保存映射操作,而且看起来速度更快(下面解释了测试以及为什么您应该采取一些预防措施)

因此,仅当您希望获得非唯一的结果,并且出于某种原因希望获得重复的结果时,才使用此选项。例如,如果您的回答可以被喜欢,并且如果您希望获得所有喜欢的数组(例如,您希望计算一些关于喜欢的统计数据):



测试。。。 这里有一些随机测试,但为了获得更值得信任的结果,应该使用大型数据库提交测试,而不是重复操作。我的意思是,据我所知,可以对重复相同查询进行任何类型的优化(很明显,映射不能有任何此类优化)

在不使用
的情况下使用
map
需要更长的时间,因此只使用
是有益的。虽然如果你根本不使用
map
的话,使用它实际上会稍微损害性能,但数据越少,似乎会使
map
运行得更快。无论如何,根据这个测试,它似乎是
与众不同的e> 在所有指标(用户、系统、总数、真实值)上都比仅使用
map
组合快10倍左右,尽管它比仅使用
而不使用
map
要慢

quids = Response.only(:_id).where(user_id: current_user.uid).map(&:_id)
Response.where(user_id: current_user.uid).distinct(:_id)
Response.where(user_id: current_user.uid).map { |r| r.likes }
Benchmark.measure { 1000.times { Organization.where(:event_labels.ne =[]).map(&:_id) } }
=>   6.320000   0.290000   6.610000 (  6.871498)
Benchmark.measure { 1000.times { Organization.where(:event_labels.ne => []).only(:_id).map(&:_id) } }
 =>   5.490000   0.140000   5.630000 (  5.981122)
Benchmark.measure { 1000.times { Organization.where(:event_labels.ne => []).distinct(:_id) } }
=>   0.570000   0.020000   0.590000 (  0.773239)
Benchmark.measure { 1000.times { Organization.where(:event_labels.ne => []).only(:_id) } }
=>   0.140000   0.000000   0.140000 (  0.141278)
Benchmark.measure { 1000.times { Organization.where(:event_labels.ne => []) } }
=>   0.070000   0.000000   0.070000 (  0.069482)