python - 我想从 MongoDB 数据中获取内部条目,但外部条目与我需要的数据一致
问题描述
我有一个如下所示的 MongoDB 数据:
{
"_id":"ObjectId(""607ddd26145c153476497e3f"")",
"official number":NumberLong(11198),
"mariners":[
{
"name":"John Williams",
"last_ship_name":"Majestic of Aberystwyth",
"this_ship_joining_port":"Llanelly",
"age":NumberLong(35),
"this_ship_leaving_cause":"Remains on board",
"this_ship_joining_date":"1850-09-21",
"place_of_birth":"Cardigan",
"additional_notes":"Remains on board",
"signed_with_mark":"N",
"this_ship_capacity":"Mate",
"last_ship_leaving_date":NumberLong(1868),
"last_ship_port":"Cardiff"
},
{
"home_address":"No info",
"name":"Edward Jones",
"last_ship_name":"Naval Reserve",
"this_ship_joining_port":"Liverpool",
"this_ship_leaving_date":"01/03/1879",
"age":"No info",
"this_ship_leaving_cause":"Discharged",
"this_ship_leaving_port":"[Hamburg?]",
"this_ship_joining_date":"1850-09",
"year_of_birth":NumberLong(1855),
"place_of_birth":"Liverpool",
"additional_notes":"Discharged - in hospital",
"signed_with_mark":"Y",
"this_ship_capacity":"$",
"last_ship_leaving_date":NumberLong(1877),
"last_ship_port":"Liverpool"
}
],
"vessel name":"Jane Ellen",
"port of registry":"Holland"
}
我试图只检索“this_ship_capacity”值并将其写入 python DataFrame 进行分析,但其他东西不断出现我需要的数据。这是我的查询:
cursor = db.data.aggregate([
{"$match":{"mariners.this_ship_capacity":{"$exists": "true"}}},
{"$project":{ "_id":0,
"mariners.this_ship_capacity":{
"$filter":{
"input": "$mariners.this_ship_capacity",
"as": "result",
"cond":{"$ne":[{"type":"$mariners.this_ship_capacity"}, "missing"]
}
}
}
}}
])
下面是输出的样子:
{u'mariners': [{u'this_ship_capacity': [u'Mate', u'$', u'Master', u'Mate']},
{u'this_ship_capacity': [u'Mate', u'$', u'Master', u'Mate']},
{u'this_ship_capacity': [u'Mate', u'$', u'Master', u'Mate']},
{u'this_ship_capacity': [u'Mate', u'$', u'Master', u'Mate']}]}
{u'mariners': [{u'this_ship_capacity': [u'Mate', u'$', u'Master', u'Mate']},
{u'this_ship_capacity': [u'Mate', u'$', u'Master', u'Mate']},
{u'this_ship_capacity': [u'Mate', u'$', u'Master', u'Mate']},
{u'this_ship_capacity': [u'Mate', u'$', u'Master', u'Mate']}]}
我只需要 Master、Mate 等的价值观,而不需要其他的东西。
解决方案
试一试这条管道。如果这不是预期的结果,请告诉我您需要的输出的确切形状。
db.data.aggregate(
[
{
$match: {
"mariners.this_ship_capacity": { $exists: true }
}
},
{
$set: {
mariners: {
$filter: {
input: "$mariners",
as: "m",
cond: { $ne: ["$$m.this_ship_capacity", "missing"] }
}
}
}
},
{
$project: {
_id: 0,
mariners: {
$map: {
input: "$mariners",
as: "m",
in: { this_ship_capacity: "$$m.this_ship_capacity" }
}
}
}
}
]
)
推荐阅读
- python - python 中的布尔值、整数和浮点 ADT 是什么?
- php - 在 php 中使用 ffmpeg 将一个 mp3 放在另一个上
- java - 使用 Jakson 解析具有相同键但不同值的 Json 响应
- c# - 请求发现坞站时出错(需要 HTTPS)
- angular - rest api wcf 启用 cors 方法不允许
- ios - 如何在 React-Native 中显示媒体文件的数量?
- angular - 显示更多/显示更少的角度指令
- flutter - Flutter.framework 源代码无法调试?
- spring-boot - ConditionalOnExpression 不适用于 FeignClient
- azure - 如何将 Azure Web App 与具有网关传输的 VNet 集成