我有一種情況,我需要通過基於總結字段值出現的數組值的操作來執行組。然後過濾計數並準備結果,以便可以根據條件顯示結果。從本質上講,如果你只是簡單地使用find函數,這些文檔就會變成如何呈現它們。由於matchedDocuments數組中收集的項目數量太多,我遇到了臨時文檔太大的問題。有關如何改善這一點的任何建議都會有所幫助。複雜的MongoDB聚合
db.collection1.aggregate([
{
'$unwind': '$arrayOfValues'
}, {
'$group': {
'_id': '$arrayOfValues',
'x_count': {
$sum: {
$cond: [{
$eq: ['$field.value', 'x']
},
1, 0
]
}
},
'y_count': {
$sum: {
$cond: [{
$eq: ['$field.value', 'y']
},
1, 0
]
}
},
'matchedDocuments': {
'$push': '$$CURRENT'
}
}
},
{'$match': {'$or': [{'x_count': {'$gte': 2}}, {'y_count': { '$gte': 1}}]}},
{'$unwind': '$matchedDocuments'},
{
'$group': {
'_id': '$matchedDocuments.key',
'document': {
'$last': '$$CURRENT.matchedDocuments'
}
}
}
], {
allowDiskUse: true
})
下面是一些樣本文檔和預期的結果基於上述標準:
// Sample documents
{ "_id" : ObjectId("5407c76b7b1c276c74f90524"), "field" : "x", "arrayOfValues" : [ "a", "b", "c" ] }
{ "_id" : ObjectId("5407c76b7b1c276c74f90525"), "field" : "x", "arrayOfValues" : [ "b", "c" ] }
{ "_id" : ObjectId("5407c76b7b1c276c74f90526"), "field" : "z", "arrayOfValues" : [ "a" ] }
{ "_id" : ObjectId("5407c76b7b1c276c74f90527"), "field" : "x", "arrayOfValues" : [ "a", "c" ] }
{ "_id" : ObjectId("5407c76b7b1c276c74f90528"), "field" : "z", "arrayOfValues" : [ "b" ] }
{ "_id" : ObjectId("5407c76b7b1c276c74f90529"), "field" : "y", "arrayOfValues" : [ "k" ] }
// Expected Result
[
{ "_id" : ObjectId("5407c76b7b1c276c74f90524"), "field" : "x", "arrayOfValues" : [ "a", "b", "c" ] }
{ "_id" : ObjectId("5407c76b7b1c276c74f90525"), "field" : "x", "arrayOfValues" : [ "b", "c" ] }
{ "_id" : ObjectId("5407c76b7b1c276c74f90527"), "field" : "x", "arrayOfValues" : [ "a", "c" ] }
{ "_id" : ObjectId("5407c76b7b1c276c74f90529"), "field" : "y", "arrayOfValues" : [ "k" ] }
]
問題無疑是用你的第一個分組鍵。但是,由於你對數組中的值進行了分組,所以你很快就會看到你實際想要在這裏做什麼。文檔樣本和預期結果通常可以最好地解釋您的意圖。 – 2014-08-27 22:50:20
我添加了示例文檔和預期結果以幫助查看問題。 – user1595702 2014-08-28 14:47:53
爲什麼不直接指望'arrayOfValues'數組大小的文檔呢?這將使聚合變得簡單,找到每個「field」值。 – wdberkeley 2014-08-29 15:44:55