MongoDB查询嵌套对象内部

huangapple go评论67阅读模式
英文:

MongoDB query inside nested objects

问题

我正在尝试查询我的文档,它看起来像这样:

"approvals": {
    "REV": "",
    "SS": "",
    "ABC": {
        "status": "Sent for approval",
        "approved_at": "",
        "approved_by": "",
    },
    "XYZ": {
        "status": "Approved",
        "approved_by": "xxx@abc.com",
        "approved_at": ISODate("2020-01-06T09:48:22.777Z"),
    },....
}

Approval 对象可以有多个子文档,如ABC、XYZ等等,我需要查询是否有任何子文档的status不是APPROVED状态。

英文:

I am trying to query my document which looks like this

"approvals" : {
    "REV" : "",
    "SS" : "",
    "ABC" : {
        "status" : "Sent for approval",
        "approved_at" : "",
        "approved_by" : "",
    },
    "XYZ" : {
        "status" : "Approved",
        "approved_by" : "xxx@abc.com",
        "approved_at" : ISODate("2020-01-06T09:48:22.777Z"),
    },....
}

The Approval object can have multiple sub documents like ABC,XYZ...etc, I need to query if this "approval" has any sub document whose "status" is not in APPROVED state

答案1

得分: 1

你需要运行 $objectToArray 来扫描你的动态键。然后,你需要使用 $anyElementTrue$map 来检查是否存在任何 Approved 值:

db.collection.find(
    { 
        $expr: { 
            $anyElementTrue: { 
                $map: { 
                    input: { $objectToArray: "$approvals" },
                    in: { $ne: [ "$$this.v.status", "Approved" ] } 
                }
            } 
        }
    }
)

Mongo Playground

英文:

You need to run $objectToArray to scan your dynamic keys. Then you need $anyElementTrue with $map to check if there's any Approved value:

db.collection.find(
    { 
        $expr: { 
            $anyElementTrue: { 
                $map: { 
                    input: { $objectToArray: "$approvals" },
                    in: { $ne: [ "$$this.v.status", "Approved" ] } 
                }
            } 
        }
})

Mongo Playground

huangapple
  • 本文由 发表于 2020年1月6日 18:35:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/59610538.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定