Details and examples of Python operations MongoDB

  • 2020-06-01 10:14:59
  • OfStack

Python operation MongoDB details and examples

Since the data in MongoDB library needs to be displayed on the page, python operation MongoDB is considered. PyMongo module is the interface package of Python to MongoDB operation, so pymongo is installed on the homepage.

1. Install the command


pip install pymongo

2. Query command:


import pymongo

#  Create a connection 
client = pymongo.MongoClient(host="10.0.2.38", port=27017)
#  The connection probeb library 
db = client['probeb']
#  Print the names of all collections in the library 
print(db.collection_names())
#  Connect to the test1 This collection 
collection = db.test1

#  This command is find rssi Is greater than srssi Less than erssi,stime Is greater than stime That is less than etime The data to stime Flashback to arrange 
sumdata = collection.find({"RSSI": {"$gt": int(srssi), "$lt": int(erssi)}, "stime": {"$gt": stime, "$lt": etime}}).sort([('stime', -1)])

# This command is find rssi Is greater than srssi Less than erssi,stime Is greater than stime Less than etime  and mac Is equal to the search or dmac Is equal to the search ( search It's a variable,  "$options":"i" It's to not differentiate search The contents of the case) data to stime Flashback to arrange 
sumdata = collection.find({"RSSI": {"$gt": int(srssi), "$lt": int(erssi)}, "stime": {"$gt": stime, "$lt": etime}, "$or": [{"mac": {"$regex": search, "$options":"i"}}, {"dmac": {"$regex": search,"$options":"i"}}]}).sort([('stime', -1)])

#  The result of the query is now assigned to sumdata , if you want to find out the specific data, you can use for cycle 
for data in sumdata:
  print(data)

#  Note: in use python operation MongoDB You can't use it when you're sorting db.test1.find().sort({"name" : 1, "age" : 1}) 
#  Otherwise, the following exception will be encountered: 
# TypeError: if no direction is specified, key_or_list must be an instance of list 
#  Solutions: 
# db.tes1t.find().sort([("name", 1), ("age" , 1)]) 
#  Reason: python Can only use lists for sorting, not dictionaries 

3. Insert data

import datetime


#  Insert data 
account = {"AccountID":1,"UserName":"libing",'date':datetime.datetime.now()}
accounts = [{"AccountID":2,"UserName":"liuw",'date':datetime.datetime.now()},
       {"AccountID":3,"UserName":"urling",'date':datetime.datetime.now()}]# Each record is inserted at a time 
 
collections.insert(account)

4. In a word, python operates MongoDB and MongoDB operate in much the same way. As long as you are familiar with the command operation of MongoDB, the operation of pymongo is not a problem.

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: