MongoDB:$将计算表达式推入$ group中 [英] MongoDB: $push a computed expression in a $group

查看:419
本文介绍了MongoDB:$将计算表达式推入$ group中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为$group操作的一部分,我想将计算的表达式推到数组上,而不是将值本身推到数组上. MongoDB可以做到这一点吗?

I'd like to push a computed expression onto an array instead of a value itself as part of a $group operation. Can MongoDB do this?

例如,如果我有一个名为c的集合,其中包含这样的文档:

For example, if I have a collection named c with documents like this:

{ "k" : 1, "v" : true }
{ "k" : 1, "v" : true }
{ "k" : 1, "v" : false }
{ "k" : 1, "v" : true }
{ "k" : 1, "v" : false }

然后我可以像这样进行聚合,以获取数组中的所有v值:

Then I can do an aggregation like this to get all v values in an array:

db.c.aggregate({$group: {_id:'$k', vals: {$push: '$v'}}})

{
    "result" : [
        {
            "_id" : 1,
            "vals" : [
                true,
                true,
                false,
                true,
                false
            ]
        }
    ],
    "ok" : 1
}

但是,如果我想将它们更改为'red''green',而不是实际的truefalse值,该怎么办?也许像这样:

But what if instead of the actual true and false values, I'd like to change them to, say, 'red' and 'green'? Perhaps something like:

db.c.aggregate({$group: {_id:'$k', vals: {$push: '$v' ? 'red' : 'green'}}})

但是,这只是输出所有'red'.可以在$push表达式中计算任意值吗?

But alas, this just outputs all 'red'. Is it possible to compute arbitrary values in a $push expression?

推荐答案

您可以使用$cond(

编辑

正如所提到的另一种编辑,实际上它需要$eq才能工作,因为{'$v':true}并未作为正确的表达式被评估.

Edit

As another edit mentioned, it actually needs $eq to work since {'$v':true} isn't evaulated as a correct expression.

这篇关于MongoDB:$将计算表达式推入$ group中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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