Python data storage series tutorials-mongodb database operations in python: connection, addition, deletion, query, modification, multi-level path, pythonmongodb

Source: Internet
Author: User
Tags mongoclient

Python data storage series tutorials-mongodb database operations in python: connection, addition, deletion, query, modification, multi-level path, pythonmongodb

Full stack engineer development manual (Author: Chen Xiaoyu)

Full python tutorial Solution

The debugging environment is python3.6. To debug python operations on mongodb databases, you must first install the mongodb database locally or on the server. Installation Reference: http://blog.csdn.net/luanpeng825485697/article/details/79353263

In python3.6, we use the pymongo library.

pip install pymongo

For how to install the python library, check the installation and uninstallation of the Python library.

After the installation is successful, you can program the code to implement python operations on the mongodb database.

Before operating the mongodb database, ensure that the mongodb service is enabled.

The code in python3.6 is as follows:

#python3.6Operation mongodb database. Please make sure the mongodb service is open before use.

Print("=====================mongodb Database=======================

From pymongo import MongoClient
From bson.objectid import ObjectId

# Connect to the database
Conn = MongoClient('127.0.0.1', 27017)
Db = conn.mydb # Specify the database name, connect to the mydb database, if not, create it automatically
My_set=db.test_set #Use test_set collection, no automatic creation

# Insert data (insert inserts a list of multiple data without traversing, high efficiency, save needs to traverse the list, insert one by one)
Users=[{"name":"zhangsan","age":18},{"name":"lisi","age":20}]
My_set.insert(users) # insert can insert an object or list of objects
User={"name":"zhangsan","age":18,'li':[1,2,3,4,5,5]}
My_set.save(user) # save can only insert one object


#return the inserted ID
Print(my_set.inserted_ids)


# Query data (returns None if not queried)
#Query all
Alluser = my_set.find() # data collection pymongo.cursor.Cursor type
#Query name=zhangsan
Alluser = my_set.find({"name":"zhangsan"})
#in the operation of the query
Alluser = my_set.find({"age":{"$in":(20,30,35)}})
# or operation when querying
Alluser = my_set.find({"$or":[{"age":20},{"age":35}]})
#all operation when querying
Alluser = my_set.find({'li':{'$all':[1,2,3,4]}}) #output...'name': 'zhangsan', 'age': 18, 'li ': [1, 2, 3, 4, 5, 6]}
#Query all records whose age is greater than 25 in the collection
Alluser = my_set.find({"age":{"$gt":15}}) #(>) Greater than - $gt, (<) Less than - $lt, (>=) Greater than or equal to - $gte (<= ) less than or equal to - $lte
# Find the type of name is String
Alluser = my_set.find({'name':{'$type':2}})
# 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



#data set
Alluser.sort([("age",1)]) ## Use the sort() method in MongoDB to sort the data. The sort() method can specify the sorted field by parameter and use 1 and -1 to specify the sort. Way, where 1 is ascending and -1 is descending.
The #limit() method is used to read the specified amount of data.
The #skip() method is used to skip the specified amount of data.
Alluser.skip(2).limit(6) #The following shows that after skipping two data, read 6

# Traversing the data set
For i in alluser:
    Print(i)
# count
Print(alluser.count())
# Query a record
Print(my_set.find_one({"name":"zhangsan"}))
Print(my_set.find_one({'_id':ObjectId('5a8fd9f047d14523ec6d377c')}))

# update data
# my_set.update(
# <query>, #Query conditions
# <update>, #update的对象 and some updated operators
# {
# upsert: <boolean>, #If there is no update record, insert it
# multi: <boolean>, #optional, mongodb defaults to false, only updates the first record found
# writeConcern: <document> #Optional, throws the level of the exception.
# }
# )

#Modify the value of the field
My_set.update({"name":"zhangsan"},{'$set':{"age":20}})
Db.col.update({'_id':ObjectId('5a8fd9f047d14523ec6d377c')},{'$set':{'age':'33'}})
# list field to add new elements
My_set.update({'name':"lisi"}, {'$push':{'li':4}}) # Add element 4 to the li field in the record named lisi
My_set.update({'name':"lisi"}, {'$push':{'li':[8,9]}}) # Add elements 4, 5 to the li field in the record whose name is lisi
# list field remove element
My_set.update({'name':"lisi"}, {'$pop':{'li':1}}) # pop Remove the last element (-1 to remove the first one)
My_set.update({'name':"lisi"}, {'pull':{'li':3}}) #pull (Remove by value) Remove 3
My_set.update({'name':"lisi"}, {'$pullAll':{'li':[1,2,3]}}) # pullAll (Remove all eligible by value)


# delete data
# my_set.remove(
# <query>, #(optional) conditions for deleted documents
# {
# justOne: <boolean>, #(optional) If set to true or 1, only one document will be deleted
# writeConcern: <document> #(optional) throws the level of the exception
# }
# )

# Delete all records of name=lisi
My_set.remove({'name': 'lisi'})

# Delete the record of an id of name=zhangsan
Id = my_set.find_one({"name":"zhangsan"})["_id"]
My_set.remove(id)

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


# ===========Multi-level path elements =========
The attribute value of the # dictionary can be another dictionary or list

# increase
Dict = {"name":"zhangsan",
       "age": 18,
       "contact" : {
           "email" : "1234567@qq.com",
           "iphone" : "11223344"},
       "contact1" : [
           {
               "email" : "111111@qq.com",
               "iphone" : "111"},
           {
               "email" : "222222@qq.com",
               "iphone" : "222"}
       ]
       }
My_set.insert(dict)

# Inquire
Users=my_set.find({"contact.iphone":"11223344"})
User = my_set.find_one({"contact.iphone":"11223344"}) # Query dictionary values
User1 = my_set.find_one({"contact1.1.iphone":"222"}) # Query array values
#print
Print(user["contact"]["email"])
#correct Result = my_set.update({"contact.iphone":"11223344"},{"$set":{"contact.email":"9999999@qq.com"}})

Result = my_set.update({"contact.1.iphone":"222"},{"$set":{"contact.1.email":"222222@qq.com"}})
Print(user1["contact1"][1]["email"])
————————————————
Copyright statement: This article is the original article of the CSDN blogger "Data Architect", following the CC 4.0 BY-SA copyright agreement, please reprint the original source link and this statement.
Original link: https://blog.csdn.net/luanpeng825485697/article/details/79354916
View comments


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.