如何解决MongoDB过滤器嵌套数组
我有一个看起来像这样的收藏集:
def stop_billing(data,context):
if 'data' in data.keys():
pubsub_data = base64.b64decode(data['data']).decode('utf-8')
pubsub_json = json.loads(pubsub_data)
cost_amount = pubsub_json['costAmount']
budget_amount = pubsub_json['budgetAmount']
else:
cost_amount = data['costAmount']
budget_amount = data['budgetAmount']
if cost_amount <= budget_amount:
print(f'No action necessary. (Current cost: {cost_amount})')
return
if PROJECT_ID is None:
print('No project specified with environment variable')
return
billing = discovery.build('cloudbilling','v1',cache_discovery=False,)
projects = billing.projects()
billing_enabled = __is_billing_enabled(PROJECT_NAME,projects)
if billing_enabled:
__disable_billing_for_project(PROJECT_NAME,projects)
else:
print('Billing already disabled')
我想通过Id来获取它,但只能使用“启用”设置,并且不确定聚合管道的外观。
我应该使用Java / Kotlin中的mongoTemplate创建查询,但是即使仅mongo查询也足够。
解决方法
//working code from MongoDB shell/CLI version 4.26(on windows 10 machine/OS)
> db.titles.find().pretty();
{
"_id" : 1,"title" : "dummy title","settings" : [
{
"type" : "light","status" : "enabled"
},{
"type" : "flare","status" : "disabled"
},{
"type" : "toolbar","status" : "enabled"
}
]
}
> db.titles.aggregate([
... {$unwind:"$settings"},... {$match:{"settings.status":"enabled"}}
... ]);
{ "_id" : 1,"settings" : { "type" : "light","status" : "enabled" } }
{ "_id" : 1,"settings" : { "type" : "toolbar","status" : "enabled" } }
> print("MongoDB: ",db.version());
MongoDB: 4.2.6
>
,
您可以使用$filter
db.collection.aggregate([
{
$project: {
_id: 1,title: 1,settings: {
$filter: {
input: "$settings",as: "item",cond: {
$eq: [
"$$item.status","enabled"
]
}
}
}
}
}
])
尝试here
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。