【问题标题】:mongodb: check condition in aggregationmongodb:检查聚合条件
【发布时间】:2023-03-16 04:08:01
【问题描述】:

我正在使用 mongodb 3.6。我的收藏中有很多文档。在文档中我没有任何 Domain 字段。我为某些文档创建 Domain。 现在我想使用聚合来过滤这个集合。也就是说,我想要那些没有 Domain 作为字段的文档。

db.Events.aggregate([
    {$project : {
        Domain : {$filter: {
            input: "$Domain",
            cond:{if: {Domain : {$exists: false}}, then: {"$BusinessCode": 1} }}}
    }
        }
],{
allowDiskUse: true
})

执行此脚本时出现错误:

Assert: command failed: {
"ok" : 0,
"errmsg" : "Unrecognized expression '$exists'",
"code" : 168,
"codeName" : "InvalidPipelineOperator"
} : aggregate failed

$filter expression 似乎不支持 $exists。 我怎么能这样做?

另一个问题是:我可以像这样使用 2 $project:

db.Events.aggregate([
    {$project : {
        Domain : {$filter: {
            input: "$Domain",
            cond:{if: {Domain : {$exists: false}}, then: {"$BusinessCode": 1} }}}
    }
        },
    {
        $match : {BusinessCode: /(([1-2]?[0-9])-([0-9]*)-([0-9]*)-([0-9]*)-([0-9]*)-([0-9]*)-([0-9]*))/}
    },
    {
        $project : {BusinessCode : {$arrayElemAt:[{$split : ["$BusinessCode", "-"]},0]}}
    },
    {
        $addFields: {"Domain":  "$BusinessCode"}
    },
],{
    allowDiskUse: true
  })

我想检查一下,文档中是否有特定字段。如果不存在,BusinessCode 投影和其他东西..

***************************编辑******************

这是我的文件样本:

"DeviceId" : "xxxxxxx",
"UserId" : UUID(""),
"UserFullName" : "test-user",
"SystemId" : "com.messaging",
"SystemTitle" : "message",
"EventId" : "messaging.message",
"EventTitle" : "test",
"EventData" : [],
"BusinessCode" : "1-2-4-4-5-6-9",...

执行此脚本后,我希望将“域”附加到我的文档中,如下所示:

"EventTitle" : "test",
"EventData" : [],
"BusinessCode" : "1-2-4-4-5-6-9"
"Domain": "1" // 1 is first number of BusinessCode that splitted

但如果 存在,则脚本会转到下一个文档并再次检查。

【问题讨论】:

  • 您能否添加一些示例文档和您的 $project 的预期结果?
  • @mickl 我更新了我的帖子
  • 谢谢,我需要再澄清一点:Domain 是 Event 内部的一个数组(您想要重塑)还是一个有时存在有时不存在的单个字段?
  • @mickl 域是一个独立的字段,应该只保存 BusinessCode 的第一个字符串。如果存在增加脚本,则响应必须拒绝将“Doamin”字段添加到其他没有此字段的文档中。
  • 谢谢,我问是因为您使用的是专用于嵌套数组的 $filter

标签: mongodb mongodb-query


【解决方案1】:

所以你在 SQL 中寻找类似 COALESCE 的东西,在 MongoDB 中它被称为 $ifNull。例如:

db.Events.save({Domain: "4"})
db.Events.save({BusinessCode: "1-2-4-4-5-6-9"})

db.Events.aggregate([
    {
        $project: {
            Domain: { 
                $ifNull: [ "$Domain", { $arrayElemAt: [ { $split : ["$BusinessCode", "-"] },0] } ] }
        }
    }
])

【讨论】:

  • 域存在时会发生什么?
  • 然后投影到最终结果中
  • COALESCE 还是 NVL?
  • @Saravana 我有 T-SQL 的背景,NVL 在 Oracle 中的工作方式类似:)
  • @mickl oh ok,Oracle COALESCE 和 NVL 是实现相同的东西,NVL 只接受 2 个 args,COALESCE 接受多个 args,第一个非 null 将返回
猜你喜欢
  • 2022-11-23
  • 1970-01-01
  • 1970-01-01
  • 2014-06-08
  • 2018-07-09
  • 2021-01-11
  • 1970-01-01
  • 2017-02-22
相关资源
最近更新 更多