如何根据条件$ push一个字段? [英] How to $push a field depending on a condition?

查看:341
本文介绍了如何根据条件$ push一个字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在MongoDB聚合管道的$ group阶段有条件地将字段推入数组.

I'm trying to conditionally push a field into an array during the $group stage of the MongoDB aggregation pipeline.

基本上,我有带有用户名的文档以及他们执行的一系列操作.

Essentially I have documents with the name of the user, and an array of the actions they performed.

如果我将用户操作分组如下:

If I group the user actions like this:

{ $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"]
}]

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

So far so good. The idea would be to now group together the actions array to see which set of user actions are the most popular. The problem is that I need to remove the "wait" action before taking into account the group. Therefore the result should be something like this, taking into account that the "wait" element should not be considered in the grouping:

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


测试#1

如果我添加此$ group阶段:


Test #1

If I add this $group stage:

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

我得到了想要的计数,但是它考虑了不需要的等待"数组元素.

I get the count that I want, but it takes into account the unwanted "wait" array element.

[{
    "_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} }}

这与我所获得的差不多,但是这将空值压入等待位置,而我不知道如何删除它们.

This is as close as I've gotten, but this pushes null values where the wait would be, and I can't figure out how to remove them.

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


更新:

我的简化文档如下:


UPDATE:

My simplified documents look like this:

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

推荐答案

您需要初步的 $match 阶段,仅选择操作"不等于等待"的那些文档.

You need a preliminary $match stage in your pipeline to select only those documents where "action" is not equals to "wait".

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

这篇关于如何根据条件$ push一个字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆