Kiran Prajapati
Kiran Prajapati

Reputation: 191

How to write queries in python script

Data :

{
  "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
}

I want to write queries in a single python script for all types of combinations in this data which gives me exact output what we want.

For example:
Suppose we want output only for fruit=Banana in Jalgaon district only, so that gives me exact output.

Suppose we want output in which district number of farmers are more than 100 , then that gives exact output.

Suppose we want output only for district=Pune, then that query gives exact output.likewise.

Any hints? How do I write queries to solve this?

Code I tried:

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

Upvotes: 1

Views: 1417

Answers (1)

P.Madhukar
P.Madhukar

Reputation: 464

Use give code to find desired output. You can create various function for your different-2 query.

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()

You can take more help from this doc:

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

Upvotes: 1

Related Questions