mongodb - 如何根据条件 $push 一个字段?

标签 mongodb mongodb-query aggregation-framework

我正在尝试在 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",
}

最佳答案

你需要一个初步的$match管道中的阶段以仅选择“操作”不等于“等待”的那些文档。

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

关于mongodb - 如何根据条件 $push 一个字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37376999/

相关文章:

javascript - 使用外部 API 调用和 findOneAndUpdate 循环结果

node.js - Node , Mongoose : Remove json element from query result with delete

mongodb - 将数组封装/转换为对象数组

node.js - MongoDB - 如何从具有 ID 的对象数组中检索多个集合

python - 从字符串中删除每个非 utf-8 符号

java - Javers MongoRepository 为 Boolean JsonPrimitive 抛出 IllegalArgumentException

c# - .NET 中的 Mongodb 单元测试

Mongodb - 多文本索引 : Index key pattern too large error code 67

mongodb - 将 $lookup 结果合并到现有数组

过滤后的 Mongodb $sample