[英]Counting embedded documents in Mongoid
我正在使用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
對象,我無法弄清楚該怎么做。
任何幫助,將不勝感激
謝謝
好。 一些開始的指示:
1)#collection轉到該類的收集對象。 因此Sheet.collection與sheet.first.collection相同。 它是整個文件收集的句柄。
2)聚合僅在調用輸出時才運行。 放一個.each {| l | pl},您會看到它會戳出結果
3)聚合可以由無限數量的操作組成。 傳遞給聚合的數組將按照發送順序執行。因此,[項目,匹配,排序]將向[匹配,排序,項目]返回不同的結果集。 您可以逐步構建並輸出圖層,以確保正確構建了圖層。
4)您需要展開嵌入式文檔以進行所需的計數( https://docs.mongodb.org/manual/reference/operator/aggregation/unwind/ )。
如果可以,請允許我為您編寫匯總,但是最好自己動手構建匯總。 您可以在mongodb網站上找到所需的所有信息。 如果需要任何幫助,請喊。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.