将不同的嵌入式结构投影到相同的名称 [英] Project different embedded structures to same name
问题描述
我正在编写一个执行以下任务的python脚本:
I am writing a python script that performs these tasks:
- 查询具有嵌入文档的MongoDB集合
- 聚合和项目以更改查询中返回的字段名称,以匹配"u_"约定
- 通过REST API将值导入ServiceNow
问题:
嵌入文档的结构不一致. HOSTNAME字段存储在不同的结构中.
The embedded documents are not in a consistent structure. The HOSTNAME field is stored in varying structures.
我需要将主机名返回为u_hostname.我需要$ hostnames.name的值(如果存在)或$ hostname的值(如果存在).
I need to return the hostname as u_hostname. I need the value of $hostnames.name if it exists OR the value of $hostname if it exists.
如何确定是否存在任何一个,并将其作为u_hostname返回?
How can I determine if either one exists, and return it as u_hostname?
结构1主机名存储为$ hostnames.name
{
"_id" : "192.168.1.1",
"addresses" : {
"ipv4" : "192.168.1.1"
},
"hostnames" : [
{
"type" : "PTR",
"name" : "example.hostname.com"
}
]
}
结构2主机名存储为$ hostname
{
"_id" : "192.168.2.1",
"addresses" : {
"ipv4" : "192.168.2.1"
},
"hostname" : "helloworld.com",
}
脚本:
查询将仅返回$ hostname的值,而不返回$ hostname.name.
The query will only return the value of $hostname, not $hostname.name.
cmp = db['computers'].aggregate([
{"$project" : {
"_id":0,
"u_hostname": "$hostnames.name",
"u_hostname": "$hostname",
"u_ipv4": "$addresses.ipv4"
}}
])
推荐答案
您可以使用 $project
主机名"字段.
You can use the $ifNull
operator to $project
the "hostname" field.
cmp = db['computers'].aggregate([
{"$project": {
"u_hostname": {
"$ifNull": [
"$hostnames.name",
{ "$map": {
"input": {"$literal": ["A"]},
"as": "el",
"in": "$hostname"
}}
]
},
"_id": 0,
"u_ipv4": "$addresses.ipv4"
}},
{"$unwind": "$u_hostname"}
])
这篇关于将不同的嵌入式结构投影到相同的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!