【发布时间】:2016-08-11 23:48:32
【问题描述】:
我正在使用 Rails + Mongoid,我有 3 个模型设置如下:
# sheet.rb
class Sheet
include Mongoid::Document
field :name, type: String
embeds_many :rows
end
# row.rb
class Row
include Mongoid::Document
field :name, type: String
embedded_in :sheet
embeds_many :cells
end
# cell.rb
class Cell
include Mongoid::Document
field :display_value, type: String
field :column_id, type: String
field :active, type: Mongoid::Boolean
embedded_in :row
end
这是一个示例工作表文档 (JSON):
{
"_id" : ObjectId("57100b713ab82964c3c17ecb"),
"name" : "Ship Tracker",
"rows": [
{
"_id" : ObjectId("57100b813ab82964c3c17f54"),
"name": "Obelisk"
"cells" : [
{
"_id" : ObjectId("57100b813ab82964c3c17f55"),
"column_id": "7263313013827459",
"display_value" : "Undocked",
"active": true
},
{
"_id" : ObjectId("57100b813ab82964c3c17f76"),
"column_id" : "7263313013827460",
"display_value" : "J7X-VN",
"active": true
}
]
},
{
"_id" : ObjectId("57100b813ab82964c3c18e3a"),
"name": "Thanatos"
"cells" : [
{
"_id" : ObjectId("57100b813ab82964c3c17f6e"),
"column_id": "7263313013827459",
"display_value" : "Undocked",
"active": true
},
{
"_id" : ObjectId("57100b813ab82964c3c17f70"),
"column_id" : "7263313013827460",
"display_value" : "NHKO-4",
"active": true
}
]
},
{
"_id" : ObjectId("57100b813ab82964c3c17f47"),
"name": "Brutix"
"cells" : [
{
"_id" : ObjectId("57100b813ab82964c3c17f66"),
"column_id": "7263313013827459",
"display_value" : "Docked",
"active": true
},
{
"_id" : ObjectId("57100b813ab82964c3c17f3c"),
"column_id" : "7263313013827460",
"display_value" : "P-T9VC",
"active": true
}
]
}
]
}
我正在尝试返回显示值的计数,但失败了。我曾尝试将聚合框架与 Mongoid 一起使用,但它似乎没有返回任何结果。
我正在使用以下代码进行聚合,但我觉得我做错了什么。我没有从 Mongoid/Ruby 收到任何错误:
query = [{'$match': {'$rows.$cells.active': true}},
{'$group': {'_id': '$rows.$cells.display_value', 'total': {'$sum': '$amount'}}}]
sheet = Sheet.first
results = sheet.collection.aggregate(query)
当我检查结果时,它返回一个Mongo::Collection::View::Aggregation 对象,我不知道该怎么处理它。
任何帮助将不胜感激
谢谢
【问题讨论】:
标签: ruby-on-rails ruby mongodb mongoid aggregation-framework