這是相當瑣碎的,我們需要做一個放鬆身心的比賽,然後一組由:
db.so.aggregate([
{ $unwind : '$attrib' },
{ $match: { 'attrib.k' : 'color' } },
{ $group: { _id: '$attrib.v', count: { '$sum': 1 } } }
]);
開卷炸燬「 attrib「數組合成一個文件:
{
"result" : [
{
"_id" : ObjectId("51eeb9f2812db9ff4412f132"),
"attrib" : {
"k" : "color",
"v" : "red"
}
},
{
"_id" : ObjectId("51eeb9f2812db9ff4412f132"),
"attrib" : {
"k" : "shape",
"v" : "rectangle"
}
},
{
"_id" : ObjectId("51eeb9f2812db9ff4412f132"),
"attrib" : {
"k" : "color",
"v" : "blue"
}
},
{
"_id" : ObjectId("51eeb9f2812db9ff4412f132"),
"attrib" : {
"k" : "avail",
"v" : true
}
}
],
"ok" : 1
}
匹配然後刪除所有非顏色項目:
{
"result" : [
{
"_id" : ObjectId("51eeb9f2812db9ff4412f132"),
"attrib" : {
"k" : "color",
"v" : "red"
}
},
{
"_id" : ObjectId("51eeb9f2812db9ff4412f132"),
"attrib" : {
"k" : "color",
"v" : "blue"
}
}
],
"ok" : 1
}
和集團最終使得其返回:
{
"result" : [
{
"_id" : "blue",
"count" : 1
},
{
"_id" : "red",
"count" : 1
}
],
"ok" : 1
}
(以上所有輸出是剛剛從你單樣本文檔)
你能多一點點的描述對哪些文件你有作爲輸入和你期望的輸出? – Derick
如果您只想計算文檔,請嘗試使用'.find({「attrib.k」:「color」})。count()'。如果你想要更復雜的文件內的發生次數,請提供更多信息,如預期輸出:) – randunel
我剛剛添加了我的預期輸出。 – joafeldmann