这是相当琐碎的,我们需要做一个放松身心的比赛,然后一组由:
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