下面是一個聚合框架回答。 請注意,第一個$匹配篩選集合級別爲 的文檔,並使用$ elemMatch來匹配數組元素的類型和可用性。 爲了完成房屋可用房間價格的總和, 不可用的房間必然被過濾掉並丟失。 $ group階段的添加字段保留用於查看的數據, 但您的應用可能更適合通過_id獲取完整文檔。
希望這回答您的問題原來的意圖 並演示聚合框架的力量。
測試/單元/ house_test.rb
require 'test_helper'
require 'pp'
class HouseTest < ActiveSupport::TestCase
def setup
House.delete_all
end
test "complex aggregate query" do
puts "\nMongoid::VERSION:#{Mongoid::VERSION}\nMoped::VERSION:#{Moped::VERSION}"
total_price_limit = 700
pipeline = [
{'$match' => {'rooms' => {'$elemMatch' => {'type' => 'single', 'available' => true}}}},
{'$unwind' => "$rooms"},
{'$match' => {'rooms.available' => true}},
{'$group' => {
'_id' => '$_id',
'description' => {'$last' => '$description'},
'total_price_available' => {'$sum' => '$rooms.price'},
'rooms' => {'$push' => '$rooms'},
}
},
{'$match' => {'total_price_available' => {'$lte' => total_price_limit}}},
{'$sort' => {'total_price_available' => 1}},
]
docs = [
{
description: 'House 1',
total_price: 1000,
rooms: [{
description: 'Small Single Room',
type: 'single',
available: true,
price: 300
}, {
description: 'Big Single Room',
type: 'single',
price: 400,
available: true
}, {
description: 'Another Room',
type: 'single',
price: 300,
available: true
}]
},
{
description: 'House 2',
total_price: 600,
rooms: [{
description: 'Small Single Room',
type: 'single',
available: true,
price: 300
}, {
description: 'Big Single Room',
type: 'single',
price: 400,
available: false
}, {
description: 'Another Room',
type: 'single',
price: 300,
available: true
}]
}
]
docs.each { |house| House.create(house) }
pp House.collection.aggregate(pipeline)
end
end
$耙測試
Run options:
# Running tests:
[1/1] HouseTest#test_complex_aggregate_query
Mongoid::VERSION:3.1.5
Moped::VERSION:1.5.1
[{"_id"=>"5272dbe2e4d30b7e0a000002",
"description"=>"House 2",
"total_price_available"=>600,
"rooms"=>
[{"description"=>"Small Single Room",
"type"=>"single",
"available"=>true,
"price"=>300},
{"description"=>"Another Room",
"type"=>"single",
"price"=>300,
"available"=>true}]}]
Finished tests in 0.046359s, 21.5708 tests/s, 0.0000 assertions/s.
1 tests, 0 assertions, 0 failures, 0 errors, 0 skips
這是一個數組。我糾正了它。臥室是一系列嵌入式文件。 –
關鍵'房間'應該是數組。類似於:'{description:'House',價格:1000,rooms:[{},{}]}' –
「可用單間,總價格爲700」 - > *精確* 700,*至少* 700或*超過* 700? – Philipp