python - 如何根据 PyMongo 中的键或子键提取值
问题描述
我有一个名为 student.json 的 json 文件,其内容如下:
{
"Student": [
{
"fees": "$21.00"
},
{
"date": "19/11/2018"
}
]
}
现在我正在尝试使用 PyMongo 提取“费用”和“日期”的值以进行进一步分析,但它不起作用。请建议。
import json
from pymongo import MongoClient
client = MongoClient('localhost', 27017)
db = client['student_db']
collection_student = db['student']
with open('student.json') as f:
file_data = json.load(f)
collection_student.insert_one(file_data)
with client:
db = client.student_db
a = db.student.find({"Student.fees": 1})
print(a.next())
在 Mongo 控制台上我试过这样:
db.student.aggregate([
{
$unwind : "$Student"
},
{
$project : {
_id : 0,
Student : 1
}
}
])
输出 :
{ "Student" : { "fees" : "$21.00" } }
{ "Student" : { "date" : "19/11/2018" } }
已编辑(1):根据建议,我尝试如下,但它正在为“日期”打印 {}。如何避免这种情况?
db.student.find({},{"Student.fees":1});
{ "_id" : ObjectId("5df3656fb3439edbccd2cca9"), "Student" : [ { "fees" : "$21.00" }, { } ] }
已编辑(2):尝试了一些它在控制台上的工作:
db.getCollection('student').find().forEach(function(student){
... ... print("Student _id : " + student._id);
... ... print("Student Key : " + JSON.stringify(student.Student[0]));
... ... print("Student Fees : " + student.Student[0].fees)
... ... print("Student Date : " + student.Student[1].date)
... ... })
Student _id : 5df3656fb3439edbccd2cca9
Student Key : {"fees":"$21.00", "date":"19/11/2018"}
Student Fees : $21.00
Student Date : 19/11/2018
解决方案
推荐阅读
- java - SpringBatch App 使用 JDBC 读取无法启动
- html - CSS 响应 1080p 及以上
- laravel - $model->get() 上 Eloquent 模型时间戳的时区错误,但 print_r() 正确
- paypal - 交易因违规而被拒绝
- android - 如何在不收到任何通知的情况下从 Firebase Cloud Messaging 仪表板发送数据?
- python - 使用另一个列表的元素创建空列表
- reactjs - 为什么 textAlign 或 align 在 reactjs 中不起作用?
- c++ - 在 C++ 复制省略期间如何管理内存?
- authentication - Asp.net 核心 API 使用 AzureAD 令牌进行身份验证
- javascript - 无法在浏览器中获取 angularJS 的输出