无法识别的管道阶段名称:“ $ and”

时间:2019-04-11 06:59:26

标签: mongodb

我试图运行两个过滤器来计算表中的男性和女性人数。我已经可以使用

对桌子上的男性或女性进行过滤和计数
db.employee.aggregate({$match:{"gender":"male"}},{$count:"Males"})

db.employee.aggregate({$match:{"gender":"female"}},{$count:"Females"})

现在,我只是试图将这两个命令组合为一个命令。在Mongodb中使用$ and怎么做?我有以下代码

db.employee.aggregate(
 { $and : 
 [  
 {$match:{"gender":"male"}},{$count:"Males"}
 ,
 {$match:{"gender":"female"}},{$count:"Females"}
 ]
 }   
 )

及其引发此错误:

E QUERY    [js] Error: command failed: {
    "ok" : 0,
    "errmsg" : "Unrecognized pipeline stage name: '$and'",
    "code" : 40324,
    "codeName" : "Location40324"
} : aggregate failed :
_getErrorWithCode@src/mongo/shell/utils.js:25:13
doassert@src/mongo/shell/assert.js:18:14
_assertCommandWorked@src/mongo/shell/assert.js:536:17
assert.commandWorked@src/mongo/shell/assert.js:620:16
DB.prototype._runAggregate@src/mongo/shell/db.js:260:9
DBCollection.prototype.aggregate@src/mongo/shell/collection.js:1062:12
@(shell):1:1

尽管我在这里做错了什么?对mondodb文档所做的仔细检查,仍然无法确定为什么会出错。

尽管如此,我仍根据文档遵循这种语法格式。

db.<collection_name>.aggregate({
 $and : [
 { <condition1>} , {condition2}
 ]
 } )

我的数据库内容可以用ff创建。脚本。

db.employee.insert([
    {"id":"1","name": "Ricardo Carpio","age": 24, "gender": "male", "birthYear" : "1995" , "hobby" : "Reading books"},
    {"id":"2","name": "Alice Salpicao","age": 27, "gender": "female", "birthYear" : "1992" , "hobby" : "Eating"},
    {"id":"3","name": "Cardo Agustin","age": 25, "gender": "male", "birthYear" : "1996" , "hobby" : "Jogging"},
    {"id":"5","name": "Gamora Yuchi","age": 24, "gender": "female", "birthYear" : "1995" , "hobby" : "Singing"},
    {"id":"6","name": "Thanos Pink","age": 29, "gender": "male", "birthYear" : "1990" , "hobby" : "Collecting gems"}
]) 

1 个答案:

答案 0 :(得分:1)

您在聚合中缺少[]。 使用db.employee.aggregate([])代替db.employee.aggregate()

尝试一下

employee.aggregate([
{
$group:{
    _id:"$gender",
    count:{$sum:1}
    }
}
])

根据您的要求,您需要使用“男”和“女”字段名称。

db.getCollection('user').aggregate([
{
$facet:{
    male:[        
            {$match:{gender:"Male"}},
            {$count:"Male"}
    ],
    female:[        
            {$match:{gender:"Female"}},
            {$count:"Female"}
    ]

    }
},
{
$unwind:{
    path:"$male",
    preserveNullAndEmptyArrays:true
    }
},
{
$unwind:{
    path:"$female",
    preserveNullAndEmptyArrays:true
    }
},
{
$project:{
    Male:{$ifNull:["$male.Male",0]},
    Female:{$ifNull:["$female.Female",0]}
    }
}
])