【问题标题】:How to $push a field depending on a condition?如何根据条件 $push 字段?
【发布时间】:2016-05-22 16:49:04
【问题描述】:

我试图在 MongoDB 聚合管道的 $group 阶段有条件地将字段推送到数组中。

基本上我有包含用户名的文档,以及他们执行的操作的数组。

如果我像这样对用户操作进行分组:

{ $group: { _id: { "name": "$user.name" }, "actions": { $push: $action"} } }

我得到以下信息:

[{
    "_id": {
        "name": "Bob"
    },
    "actions": ["add", "wait", "subtract"]
}, {
    "_id": {
        "name": "Susan"
    },
    "actions": ["add"]
}, {
    "_id": {
        "name": "Susan"
    },
    "actions": ["add, subtract"]
}]

到目前为止一切顺利。现在的想法是将操作数组组合在一起,以查看哪些用户操作集最受欢迎。问题是我需要在考虑组之前删除“等待”操作。因此,考虑到分组中不应考虑“等待”元素,结果应该是这样的:

[{
    "_id": ["add"],
    "total": 1
}, {
    "_id": ["add", "subtract"],
    "total": 2
}]

测试 #1

如果我添加这个 $group 阶段:

{ $group : { _id : "$actions", total: { $sum: 1} }}

我得到了我想要的计数,但它考虑了不需要的“等待”数组元素。

[{
    "_id": ["add"],
    "total": 1
}, {
    "_id": ["add", "subtract"],
    "total": 1
}, {
    "_id": ["add", "wait", "subtract"],
    "total": 1
}] 

测试#2

{ $group: { _id: { "name": "$user.name" }, "actions": { $push: { $cond: { if: 
{ $ne: [ "$action", 'wait']}, then: "$action", else: null } }}} }


{ $group : { _id : "$actions", total: { $sum: 1} }}

这与我得到的一样接近,但这会将空值推送到等待的位置,我不知道如何删除它们。

[{
    "_id": ["add"],
    "total": 1
}, {
    "_id": ["add", "subtract"],
    "total": 1
}, {
    "_id": ["add", null, "subtract"],
    "total": 1
}]

更新:

我的简化文档如下所示:

{
    "_id": ObjectID("573e0c6155e2a8f9362fb8ff"),
    "user": {
        "name": "Bob",
    },
    "action": "add",
}

【问题讨论】:

  • 您能出示您的原始文件吗?
  • @user3100115 我已经更新了问题
  • 所以你不想在数组中“等待”。对吗?
  • @user3100115 没错。我希望能够删除等待作为操作的文档,并且只考虑其余的。有什么方法可以在管道的 $group 阶段执行此操作,还是只能使用 $match 来实现?

标签: mongodb mongodb-query aggregation-framework


【解决方案1】:

您需要在管道中设置一个初步的$match 阶段,以仅选择“action”不等于“wait”的那些文档。

db.collection.aggregate([
    { "$match": { "action": { "$ne": "wait" } } },
    { "$group": { 
        "_id": "$user.name", 
       "actions": { "$push": "$action" }, 
       "total": { "$sum": 1 } 
    }}
])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-10-13
    • 1970-01-01
    • 2020-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-15
    相关资源
    最近更新 更多