$cond 中 $exists 的条件分组 [英] Conditional grouping with $exists inside $cond

查看:22
本文介绍了$cond 中 $exists 的条件分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个键 A 和 B,它们在文档中的存在是互斥的.当 A 存在时我必须按 A 分组,当 B 存在时我必须按 B 分组.因此,我将$project 所需的值输入到一个名为 MyKey 的计算键中,我将在该键上执行 $group.但看起来我在语法上犯了一个错误.我尝试以两种方式编写 $project:

<代码>{$project: {MyKey: {$cond: [{$exists: ["$A", true]}, "$A", "$B"]}}}

{$project: {MyKey: {$cond: [{"A": {$exists:true}}, "$A", "$B"]}}}

但我一直收到错误:

{ "errmsg" : "exception: invalid operator '$exists'", "code" : 15999, "ok" : 0 } ...

怎么了?

解决方案

使用 $ifNull 而不是 $cond 在您的 $project 中:

{ $project: {MyKey: {$ifNull: ['$A', '$B'] }}}

如果 A 存在且不是 null,则将使用其值;否则使用 B 的值.

I have two keys A and B and their existence in the document is mutually exclusive. I have to group by A when A exists and group by B when B exists. So I am $projecting the required value into a computed key called MyKey on which I'll perform a $group. But it looks like I'm making a mistake with the syntax. I tried writing $project in two ways:

{$project: {MyKey: {$cond: [{$exists: ["$A", true]}, "$A", "$B"]}}}

and

{$project: {MyKey: {$cond: [{"A": {$exists:true}}, "$A", "$B"]}}}

But I keep getting the error:

{ "errmsg" : "exception: invalid operator '$exists'", "code" : 15999, "ok" : 0 } ...

What's going wrong?

解决方案

Use $ifNull instead of $cond in your $project:

{ $project: {MyKey: {$ifNull: ['$A', '$B'] }}}

If A exists and is not null its value will be used; otherwise the value of B is used.

这篇关于$cond 中 $exists 的条件分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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