尝试 1:(这只返回总数)
db.collection.aggregate([
{
$match: {
"dob.age": 59
}
},
{
$count: "total"
},
{
$project: {
"dob.age": 1,
"total":1
}
}
])
尝试 2(异常 - 管道阶段规范对象必须恰好包含一个字段)
db.collection.aggregate([
{
$match: {
"dob.age": 59
}
},
{
$count: "total",
"dob.age": 1
}
])
尝试 3(空对象):
db.collection.aggregate([
{
$match: {
"dob.age": 59
}
},
{
$group: {
_id: null,
total: {
$sum: 1
}
}
},
{
$project: {
_id: 0,
"dob.age": 1
}
}
])
你可以这样做 - 相当于$count
db.collection.aggregate([
{
$match: { //match condition
"dob.age": 59
}
},
{
$group: {//$count equivalent
_id: null,
myCount: {
$sum: 1
},
"data": {//all other fields
$push: "$$ROOT"
}
}
},
{
$project: {//removing null id - you can skip this if null id is not a problem
_id: 0
}
}
])
如果你运行
match:"dob.age": 59
输出年龄将是一个常数 59.
在任何情况下,您都需要按年龄运行分组,这样您将获得按年龄排列的总行数:
db.collection.aggregate([
{
$match: {
"dob.age": 59
}
},
{
$group: {
_id: "$dob.age",
total: {
$sum: 1
}
}
},
{
$project: {
_id: 0,
age: "$_id",
"total": 1
}
}
])
否则我建议简单地运行:
db.collection.count({"dob.age": 59}) // it will be 2 as well