monogid pluck返回嵌入/嵌套字段的重复结果

时间:2017-04-11 22:26:14

标签: ruby-on-rails mongodb mongoid

Monogoid pluck为嵌入字段返回重复的嵌入结果(不关心重复行)。

例如:(用户是SomeModel的嵌入式文档)

SomeModel.where(condition).pluck(:region, "user.name", "user.lastname")

Results:
[["amr", 
  {"name" => "mark", "lastname" => "goodman"},
  {"name" => "mark", "lastname" => "goodman"}],
 ["amr", 
  {"name" => "john", "lastname" => "cena"},
  {"name" => "john", "lastname" => "cena"}]
]

我期待下面的事情:

[["amr",
  {"name" => "mark"},
  {"lastname" => "goodman"}],
 ["amr",
  {"name" => "john"},
  {"lastname" => "cena"}]
]

同样,如果我从嵌入式文档查询多个字段,它会创建许多重复的哈希值。

不确定我在这里做错了什么。

1 个答案:

答案 0 :(得分:0)

我不确定为什么会这样,但您可以使用map代替pluck来获得所需的结果:

SomeModel.where(condition).map { |m| [m.region, m.user.name, m.user.lastname] }

这应该给你结果:

[
  ["amr", "mark", "goodman"],
  ["amr", "john", "cena"]
]

或者:

SomeModel.where(condition).map do |m|
  [m.region, { 'name' => m.user.name }, { 'lastname' => m.user.lastname }]
end

应该给你结果:

[
  ["amr", { "name" => "mark" }, { "lastname" => "goodman" }],
  ["amr", { "name" => "john" }, { "lastname" => "cena" }]
]