我有两个键 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
而不是 $project
中的 $cond
:
{ $project: {MyKey: {$ifNull: ['$A', '$B'] }}}
如果 A
存在且不为 null
,则使用其值;否则使用 B
的值。
https://stackoverflow.com/questions/14213636/
相关文章:
javascript - Node.js - 等待多个异步调用
mongodb - 如何在不丢失数据的情况下调整 mongodb 上限集合的大小?
sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
mongodb - 在 MongoDB 中创建自定义对象 ID
node.js - 如何检查MongoDB native nodejs驱动程序中是否存在集合?
c# - MongoDB C# 驱动程序 : Ignore Property on Insert
php - 安装 PHP 7 MongoDB 客户端/驱动程序?
sql - 为什么 MongoDB 比 SQL DB 快得多的任何详细和具体原因?