MongoDB,多个计数(带有$ exists) [英] MongoDB, Multiple count (with $exists)
问题描述
我有以下3个请求:
db.mycollection.count({requestA:{$exists:true}})
db.mycollection.count({requestB:{$exists:true}})
db.mycollection.count({requestC:{$exists:true}})
我只想提出一个请求... 所以我尝试了以下方法:
I'd like to make only one request... So i tried the following:
db.mycollection.aggregate( [
{ $group: {
'_id' : { user_id: '$user_id'},
requestA_count: { $sum: {
$cond: [ {requestA:{'$exists':true}}, 1, 0 ]
} },
requestB_count: { $sum: {
$cond: [ {requestB:{'$exists':true}}, 1, 0 ]
} },
requestC_count: { $sum: {
$cond: [ {requestC:{'$exists':true}}, 1, 0 ]
} },
} },
{ $project: {
_id: 0,
user_id: '$_id.user_id',
requestA_count: 1,
requestB_count: 1,
requestC_count: 1
} }
] );
但是我得到了错误:
"errmsg" : "exception: invalid operator '$exists'",
我想我们不能将$ exists与$ project一起使用.
I guess that we cannot use $exists with $project.
有关好的方法的任何提示吗?谢谢
Any tips about a good approach ? Thank you
推荐答案
您有正确的基本概念,但 $exists
是一个查询条件,因此仅在 $ifNull
运算符同一件事:
You had the right basic idea but $exists
is a query condition so is only valid witin a $match
. What you want is the $ifNull
operator to essentially do the same thing:
db.mycollection.aggregate( [
{ "$group": {
"_id" : { "user_id": "$user_id" },
"requestA_count": { "$sum": {
"$cond": [ { "$ifNull": ["$requestA", false] }, 1, 0 ]
} },
"requestB_count": { "$sum": {
"$cond": [ { "$ifNull": ["$requestB", false] }, 1, 0 ]
} },
"requestC_count": { "$sum": {
"$cond": [ { "$ifNull": ["$requestC", false] }, 1, 0 ]
} },
} },
{ "$project": {
"_id": 0,
"user_id": "$_id.user_id",
"requestA_count": 1,
"requestB_count": 1,
"requestC_count": 1
} }
] );
因此 $ifNull
要么返回当前值字段的值(如果存在),或者如果不存在,则返回右侧"参数.除了false
之外的返回值都被解释为true
(当然,除非该值实际上为false).
So the $ifNull
either returns the present value of the field if it exists or the "right side" argument is returned if it does not. The returned value other than false
is intrepreted as being true
( unless of course the value is actually false ).
从本质上讲,这为您提供了逻辑上测试文档中属性是否存在的相同功能.
Essentially this gives you the same functionality of logically testing for the existence of a property in the document.
这篇关于MongoDB,多个计数(带有$ exists)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!