我关注了@Blakes-Seven 的这篇文章 Mongodb 聚合多个日期范围的$group
但是我需要按字段“$User.Account”添加一个额外的组,并且我不断收到错误。当我把它拿出来时,效果很好。
我正在尝试做的事情是找到每个日期范围内的前 N 个用户......
{
"message" : "the group aggregate field 'User' must be defined as an expression inside an object",
"ok" : 0,
"code" : 15951,
"name" : "MongoError"
}
任何帮助将不胜感激。我错过了一些东西...
> // work out dates somehow var today = new Date(),
> oneDay = ( 1000 * 60 * 60 * 24 ),
> ninetyDays = new Date( today.valueOf() - ( 90 * oneDay ) ),
> sixtyDays = new Date( today.valueOf() - ( 60 * oneDay ) ),
> thirtyDays = new Date( today.valueOf() - ( 30 * oneDay ) );
>
> db.logs.aggregate([
> { "$match": {
> "DateTime": { "$gte": ninetyDays },
> "Orgname": /Inc/
> }},
> { "$group": {
> "_id": {
> "$cond": [
> { "$lt": [ "$DateTime", sixtyDays ] },
> "61-90",
> { "$cond": [
> { "$lt": [ "$DateTime", thirtyDays ] },
> "31-60",
> "01-30"
> ]}
> ]
> },
> "User": "$User.Account",
> "count": { "$sum": 1 },
> }},
> { $sort: {"count": -1}
> },
> { $limit: 25} ])
Sample output
01-30 usera 45
01-30 userc 34
01-30 userf 28
01-30 userq 13
… 20 more rows...
01-30 usery 4
31-60 userb 55
… 23 more rows
31-60 userk 3
61-90 userm 78
61-90 userf 45
... 22 more rows...
61-90 usery 22
您可以按照以下语法在
$group
表达式中添加另一个字段
db.logs.aggregate([
{ "$match": {
"DateTime": { "$gte": ninetyDays },
"Orgname": /Inc/
}},
{ "$group": {
"_id": {
"User": "$User.Account",
"date": {
"$cond": [
{ "$lt": [ "$DateTime", sixtyDays ] },
"61-90",
{ "$cond": [
{ "$lt": [ "$DateTime", thirtyDays ] },
"31-60",
"01-30"
]}
]
}
},
"count": { "$sum": 1 },
}},
{ "$sort": { "count": -1 }},
{ "$limit": 25}
])
希望这个例子有帮助
db.collection.aggregate([
{
$group: {
_id: {
"type": "$type",
$cond: {
if: { $in: ["$category", [1, 2]] },
then: "$category",
else: "$otherField" // Replace "otherField" with the actual name of your second field## Heading ##
}
},
count: { $sum: 1 }
}
}
])
$in 可以替换为 $eq $nin 和其他所需的约束