首页 > 解决方案 > 如何根据 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

标签: pythonjsonpython-3.xmongodbpymongo

解决方案


推荐阅读