Using pymongo to operate the database

Using pymongo to connect to the database

Connect mongodb

#!/usr/bin/env python
# -*- coding:utf-8 -*-

from pymongo import MongoClient

conn = MongoClient('192.168.0.113', 27017)
db = conn.mydb  #Connect to mydb database, if not, it will be created automatically
my_set = db.test_set  #Use the test set collection, otherwise it will be created automatically

Insert data (insert inserts a list, multiple pieces of data do not need to traverse, high efficiency, save needs to traverse the list, insert one by one)

my_set.insert({"name":"zhangsan","age":18})
#or
my_set.save({"name":"zhangsan","age":18})

Insert multiple

#Add multiple pieces of data to the collection
users=[{"name":"zhangsan","age":18},{"name":"lisi","age":20}]  
my_set.insert(users) # Insert is out of date. It is recommended to use insert [one] or insert [many] to insert
#or
my_set.save(users) 

Query data (if not found, return None)

#Query all
 #Using find to return a courier object, you can use for loop to traverse to get specific results
 You can also use tour. Next () to gradually get the next object
for i in my_set.find():
    print(i)
#Query name=zhangsan's
for i in my_set.find({"name":"zhangsan"}):
    print(i)
Print (my set. Find one ({name ":" Zhangsan "})) (find one returns a specific object

Update data

my_set.update(
   <query>,    #query criteria
   <update>,    #Update object and some update operators
   {
     upsert: <boolean>,    #If there is no record of update, insert
     multi: <boolean>,        #Optional. mongodb is false by default. Only the first record found is updated
     writeConcern: <document>    #Optional, the level at which the exception is thrown.
   }
)

Change the age of the data inserted above to 20

my_set.update({"name":"zhangsan"},{'$set':{"age":20}})

Delete data

my_set.remove(
   <query>,    #(optional) conditions for deleted documents
   {
     justOne: <boolean>,    #(optional) if set to true or 1, only one document is deleted
     writeConcern: <document>    #(optional) level of exception thrown
   }
)
#Delete all records with name=lisi
my_set.remove({'name': 'zhangsan'})

#Delete a record with an id of name=lisi
id = my_set.find_one({"name":"zhangsan"})["_id"]
my_set.remove(id)

#Delete all records in the collection
db.users.remove()

Conditional operators of mongodb

#    (>) greater than - $gt
#    (< less than - $lt
#    (> =) greater than or equal to - $gte
#    (< =) less than or equal to - $lte

#Example: query all records with age greater than 25 in the collection
for i in my_set.find({"age":{"$gt":25}}):
    print(i)

Type (judgment type)

#Find out the type of name isStringWe'll only find out name Is of type string
for i in my_set.find({'name':{'$type':2}}):
    print(i)

type Comparison table

Double    1     
String    2     
Object    3     
Array    4     
Binary data    5     
Undefined    6    obsolete
Object id    7     
Boolean    8     
Date    9     
Null    10     
Regular Expression    11     
JavaScript    13     
Symbol    14     
JavaScript (with scope)    15     
32-bit integer    16     
Timestamp    17     
64-bit integer    18     
Min key    255    Query with -1.
Max key    127

sort
In MongoDB, sort() method is used to sort the data. Sort() method can specify the sorting field by parameter, and use 1 and - 1 to specify the sorting method, where 1 is ascending and - 1 is descending.

for i in my_set.find().sort([("age",1)]):
    print(i)

limit and skip

#The limit() method is used to read a specified amount of data
#The skip() method is used to skip a specified amount of data
#The following indicates that six data will be read after two data are skipped
for i in my_set.find().skip(2).limit(6):
    print(i)

IN

#Find out that the data in which age is 20, 30 and 35 is followed by a tuple
for i in my_set.find({"age":{"$in":(20,30,35)}}):
    print(i)

OR

#Find out that the recorder with age 20 or 35 is followed by a list
for i in my_set.find({"$or":[{"age":20},{"age":35}]}):
    print(i)

all

'''
dic = {"name":"lisi","age":18,"li":[1,2,3]}
dic2 = {"name":"zhangsan","age":18,"li":[1,2,3,4,5,6]}

my_set.insert(dic)
my_set.insert(dic2)'''
for i in my_set.find({'li':{'$all':[1,2,3,4]}}):  
    print(i)
#See if all conditions are included
#Output: {'_id': ObjectId('58c503b94fc9d44624f7b108'), 'name': 'zhangsan', 'age': 18, 'li': [1, 2, 3, 4, 5, 6]}

push/pushAll

my_set.update({'name':"lisi"}, {'$push':{'li':4}})
for i in my_set.find({'name':"lisi"}):
    print(i)
#Output: {'li': [1, 2, 3, 4], '_id': ObjectId('58c50d784fc9d44ad8f2e803'), 'age': 18, 'name': 'lisi'}

my_set.update({'name':"lisi"}, {'$pushAll':{'li':[4,5]}})
for i in my_set.find({'name':"lisi"}):
    print(i)
#Output: {'li': [1, 2, 3, 4, 4, 5], 'name': 'lisi', 'age': 18, '_id': ObjectId('58c50d784fc9d44ad8f2e803')}

pop/pull/pullAll

#pop
#Remove the last element (- 1 is the first to remove)
my_set.update({'name':"lisi"}, {'$pop':{'li':1}})
for i in my_set.find({'name':"lisi"}):
    print(i)
#Output: {'_id': ObjectId('58c50d784fc9d44ad8f2e803'), 'age': 18, 'name': 'lisi', 'li': [1, 2, 3, 4, 4]}

#pull (remove by value)
#remove3
my_set.update({'name':"lisi"}, {'$pop':{'li':3}})

#pullAll (remove all eligible)
my_set.update({'name':"lisi"}, {'$pullAll':{'li':[1,2,3]}})
for i in my_set.find({'name':"lisi"}):
    print(i)
#Output: {'name': 'lisi', '_id': ObjectId('58c50d784fc9d44ad8f2e803'), 'li': [4, 4], 'age': 18}

Multi level path element operation

Insert a piece of data first

dic = {"name":"zhangsan",
       "age":18,
       "contact" : {
           "email" : "1234567@qq.com",
           "iphone" : "11223344"}
       }
my_set.insert(dic)
#For multi-level directory. Connection
for i in my_set.find({"contact.iphone":"11223344"}):
    print(i)
#Output: {'name': 'zhangsan', '_id': ObjectId('58c4f99c4fc9d42e0022c3b6'), 'age': 18, 'contact': {'email': '1234567@qq.com', 'iphone': '11223344'}}

result = my_set.find_one({"contact.iphone":"11223344"})
print(result["contact"]["email"])
#Output:1234567@qq.com

#Modify in multi-level path
result = my_set.update({"contact.iphone":"11223344"},{"$set":{"contact.email":"9999999@qq.com"}})
result1 = my_set.find_one({"contact.iphone":"11223344"})
print(result1["contact"]["email"])
#Output:9999999@qq.com

You can also index arrays

dic = {"name":"lisi",
       "age":18,
       "contact" : [
           {
           "email" : "111111@qq.com",
           "iphone" : "111"},
           {
           "email" : "222222@qq.com",
           "iphone" : "222"}
       ]}
my_set.insert(dic)
#query
result1 = my_set.find_one({"contact.1.iphone":"222"})
print(result1)
#Output: {'age': 18, '_id': ObjectId('58c4ff574fc9d43844423db2'), 'name': 'lisi', 'contact': [{'iphone': '111', 'email': '111111@qq.com'}, {'iphone': '222', 'email': '222222@qq.com'}]}

#modify
result = my_set.update({"contact.1.iphone":"222"},{"$set":{"contact.1.email":"222222@qq.com"}})
print(result1["contact"][1]["email"])
#Output:222222@qq.com

Tags: MongoDB Database less Javascript

Posted on Tue, 31 Mar 2020 12:32:13 -0700 by m@ndio