如何避免在mongo聚合框架中使用$ push-ing nulls [英] how to avoid $push-ing nulls in mongo aggregation framework

查看:71
本文介绍了如何避免在mongo聚合框架中使用$ push-ing nulls的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果不存在该字段,则$ push会聚合null. 我想避免这种情况.

$push is aggregating nulls if the field is not present. I would like to avoid this.

有没有一种方法可以使$ push运算符成为子表达式,从而跳过空值而不将其推入结果数组中?

Is there a way to make a sub expression for $push operator in such way that null values will be skipped and not pushed into the resulting array ?

推荐答案

晚点,但是..

我想做同样的事情,发现我可以用这样的表达式来完成它:

I wanted to do the same thing, and found that I could accomplish it with an expression like this:

  // Pushes events only if they have the value 'A'
  "events": {
    "$push": {
      "$cond": [
        {
          "$eq": [
            "$event",
            "A"
          ]
        },
        "A",
        "$noval"
      ]
    }
  }

这里的想法是,当您这样做

The thinking here is that when you do

{ "$push": "$event" } 

然后似乎只推送非null值.

then it seems to only push non-null values.

因此,我创建了一个不存在的列$ noval,作为我的$ cond的错误条件返回.

So I made up a column that doesn't exist, $noval, to be returned as the false condition of my $cond.

似乎可行.我不确定这是否是非标准的,因此容易折断一天...

It seems to work. I'm not sure if it is non-standard and therefore susceptible to breaking one day but..

这篇关于如何避免在mongo聚合框架中使用$ push-ing nulls的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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