英文:
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" ] }
}
}
}
}
)
英文:
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" ] }
}
}
}
})
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论