我的收藏看起来会这样
{
"_id" : ObjectId("55c8bd1d85b83e06dc54c0eb"),
"name" : "xxx",
"salary" : 10000,
"type" : "type1"
}
{
"_id" : ObjectId("55c8bd1d85b83e06dc54c0eb"),
"name" : "aaa",
"salary" : 10000,
"type" : "type2"
}
{
"_id" : ObjectId("55c8bd1d85b83e06dc54c0eb"),
"name" : "ccc",
"salary" : 10000,
"type" : "type2"
}
我的查询参数将会出现,
{salary = 10000,type = type2}
所以基于查询,我需要获取上述查询参数的数量
结果应该是这样的,
{类别:“类型1”,计数:500} {类别:“类型2”,计数:200} {类别:“名称”,计数:100}
现在,我通过命中三个不同的查询并构造结果(或)服务器端迭代来获得计数。
任何人都可以建议或提供我获得上述结果的好方法
您提出的问题不是很清楚,但是您似乎想要在此处进行的操作是对字段中数据的出现进行计数,可以选择通过匹配条件的值来过滤这些字段。
db.collection.aggregate([
{ "$group": {
"_id": null,
"name": { "$sum": 1 },
"salary": {
"$sum": {
"$cond": [
{ "$gte": [ "$salary", 1000 ] },
1,
0
]
}
},
"type": {
"$sum": {
"$cond": [
{ "$eq": [ "$type", "type2" ] },
1,
0
]
}
}
}}
])
所有值都在同一文档中,在这里将它们拆分实际上没有任何意义,因为这是管道中的其他工作。
{ "_id" : null, "name" : 3, "salary" : 3, "type" : 2 }
否则为长格式,由于需要为每个键制作每个文档的副本,因此效果不佳,如下所示:
db.collection.aggregate([
{ "$project": {
"name": 1,
"salary": 1,
"type": 1,
"category": { "$literal": ["name","salary","type"] }
}},
{ "$unwind": "$category" },
{ "$group": {
"_id": "$category",
"count": {
"$sum": {
"$cond": [
{ "$and": [
{ "$eq": [ "$category", "name"] },
{ "$ifNull": [ "$name", false ] }
]},
1,
{ "$cond": [
{ "$and": [
{ "$eq": [ "$category", "salary" ] },
{ "$gte": [ "$salary", 1000 ] }
]},
1,
{ "$cond": [
{ "$and": [
{ "$eq": [ "$category", "type" ] },
{ "$eq": [ "$type", "type2" ] }
]},
1,
0
]}
]}
]
}
}
}}
])
它的输出是:
{ "_id" : "type", "count" : 2 }
{ "_id" : "salary", "count" : 3 }
{ "_id" : "name", "count" : 3 }
如果您的文档没有统一的键名,或者无法在管道条件中指定每个键,请使用mapReduce代替:
db.collection.mapReduce(
function() {
var doc = this;
delete doc._id;
Object.keys(this).forEach(function(key) {
var value = (( key == "salary") && ( doc[key] < 1000 ))
? 0
: (( key == "type" ) && ( doc[key] != "type2" ))
? 0
: 1;
emit(key,value);
});
},
function(key,values) {
return Array.sum(values);
},
{
"out": { "inline": 1 }
}
);
它的输出是:
"results" : [
{
"_id" : "name",
"value" : 3
},
{
"_id" : "salary",
"value" : 3
},
{
"_id" : "type",
"value" : 2
}
]
对于条件计数,这基本上是相同的,只是您仅指定所需条件的“反向”,并且仅针对要在其上过滤条件的字段。当然,此输出格式很容易作为单独的文档发出。
相同的方法适用于要在您要为其满足条件的字段上测试条件是否满足的情况,并返回1
满足条件或不满足条件0
的总和。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句