我有这个收藏集:
// collection
[
{_id: 1, name: 'Luigi', childs: [{name: 'one'}, {name: 'two'}], dad_id: 9]},
{_id: 1, name: 'Mario', childs: [{name: 'four'}, {name: 'five'}], dad_id: 8]},
{_id: 1, name: 'Alessandro', childs: [{name: 'seven'}, {name: 'six'}], dad_id: 9]},
]
并对其应用此过滤器
result = collection.find({ dad_id: 9 })
然后,我想汇总结果并单独获得所有孩子,我首先展开它们
(然后我将进行投影等),但是我已经遇到一种我不理解的行为:
结果还包含dad_id
为8的文档,即使它们已被我的查询排除。
result.aggregate([
{ "$unwind"=> "$childs" },
]).each do |e| ... end
// => [
{_id: 1, name: 'Luigi', childs: {name: 'one'}, dad_id: 9]},
{_id: 1, name: 'Luigi', childs: {name: 'two'}, dad_id: 9]},
{_id: 1, name: 'Luigi', childs: {name: 'five'}, dad_id: 8]},
{_id: 1, name: 'Luigi', childs: {name: 'four'}, dad_id: 8]},
{_id: 1, name: 'Luigi', childs: {name: 'seven'}, dad_id: 9]},
{_id: 1, name: 'Luigi', childs: {name: 'six'}, dad_id: 9]},
]
我想念什么?
答案 0 :(得分:0)
您不能像这样将输入从一个查询链接到另一个查询。
使用搜索查询ex。 Model.find(id)或聚合框架。
Aggregation framework为您提供创建管道的功能(例如match,unwind,lookup,project)。
要利用mongodb索引,请始终首先在管道中使用“ $ match”
match = { "$match" => { "dad_id" =>9} }
unwind = {"$uwind"=>"$childs"}
pipeline = [match,unwind]
collection.aggregate(pipeline).each do |obj|
end