python - 如何在Python脚本中编写查询

标签 python mongodb mongodb-query pymongo mongoengine

数据:

{
  "Fruit": "Pomegranate",
  "District": "Nasik",
  "Taluka": "Nasik",
  "Revenue circle": "Nasik",
  "Sum Insured": 28000,
  "Area": 1200,
  "Farmer": 183
}

{
  "Fruit": "Pomegranate",
  "District": "Jalna",
  "Taluka": "Jalna",
  "Revenue circle": "Jalna",
  "Sum Insured": 28000,
  "Area": 120,
  "Farmer": 13
}

{
  "Fruit": "Guava",
  "District": "Pune",
  "Taluka": "Haveli",
  "Revenue circle": "Uralikanchan",
  "Sum Insured": 50000,
  "Area": 10,
  "Farmer": 100
}

{
  "Fruit": "Guava",
  "District": "Nasik",
  "Taluka": "Girnare",
  "Revenue circle": "Girnare",
  "Sum Insured": 50000,
  "Area": 75,
  "Farmer": 90
}

{
  "Fruit": "Banana",
  "District": "Nanded",
  "Taluka": "Nandurbar",
  "Revenue circle": "NandedBK",
  "Sum Insured": 5000,
  "Area": 2260,
  "Farmer": 342
}

{
  "Fruit": "Banana",
  "District": "Jalgaon",
  "Taluka": "Bhadgaon",
  "Revenue circle": "Bhadgaon",
  "Sum Insured": 5000,
  "Area": 220,
  "Farmer": 265
}

我想在一个 python 脚本中为该数据中的所有类型的组合编写查询,这可以为我提供我们想要的准确输出。

例如:
假设我们只需要 Jalgaon 区的 Fruit=Banana 的输出,这样就可以得到准确的输出。

假设我们想要该地区农民数量超过 100 的输出,那么就给出了准确的输出。

假设我们只需要 District=Pune 的输出,那么该查询会给出准确的输出。同样。

有什么提示吗?如何编写查询来解决这个问题?

我尝试过的代码:

import pymongo 
connection = pymongo.MongoClient("mongodb://localhost") 
db=connection.book 
record1 = db.book_collection 
cursor = record1.find({"Fruit":"Banana"},{"Fruit":True, "_id":False, "Farmer":True}) 
for doc in cursor: 
    print doc # but there I need one python file for one query

最佳答案

使用给定的代码查找所需的输出。您可以为 different-2 查询创建各种函数。

import pymongo

class DbQuery(object):
    def __init__(self, ):
        self.mongo_client = pymongo.MongoClient("localhost", 27017)

    def findQuery(self):
        mongo_db = self.mongo_client["book"]

        cursor = mongo_db["book_collection"].find({"Fruit":"Guava"},{"Fruit":1})

        for document in cursor:
            # print document['District']
            print document['Fruit']


if __name__ == '__main__':
    obj = DbQuery()
    obj.findQuery()

您可以从此文档中获得更多帮助:

  1. https://docs.mongodb.com/manual/crud/

关于python - 如何在Python脚本中编写查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41219058/

相关文章:

python - 了解汉诺塔的 Python

c# - MongoRepository 继承序列化错误

node.js - Mongoose,文本搜索多个字段不起作用

嵌套数组的 MongoDB 投影

node.js - 在mongodb聚合中仅提取$project中键值对中的值

python - 如何从 pandas DF 获取 `field_name:field_type` 的字典

Python:捕获对内存中文件的所有写入

mongodb - 是否可以在同一查询中使用运算符 "$ne"和 "$elemMatch"?

python - 如何以编程方式将 csv 导入 Excel 并使用 Excel 格式?

mongodb - 从azure中的mongodb数据库中删除一行