Python backend: MongoDB database

table of Contents

 

1 Introduction

2. pip installation

3. Create a database

4. Determine whether the database exists

5. Create a collection (there is no concept of data tables in MongoDB, collectively referred to as collections)

6. Determine whether the collection exists

7. Add, delete, modify, and check operations

One, add data

Two, query data

Three, modify the data

Four, delete data

Five, view the table


1 Introduction

MongoDB is currently one of the most popular NoSQL databases, using the data type BSON (similar to JSON).

2. pip installation

Install pymongo:

pip install pymongo

# 也可指定安装的版本
pip install pymongo==3.5.1

# 更新pymongo
pip install --upgrade pymongo

3. Create a database

To create a database, you need to use the MongoClient object, and specify the URL address of the connection and the name of the database to be created.

Such as:

import pymongo

myclient=pymongo.MongoClient("mongodb://localhost:27017/")
mydb=myclient["runoobdb"]

# 注:MongoDB中,数据库只有在内容插入后才会创建,就是说,数据库创建后要创建集合(数据表)
并插入一个文档(记录),数据库才会真正创建。

4. Determine whether the database exists

import pymongo
myclient=pymongo.MongoClient("mongodb://localhost:27017/")
dblist=myclient.list_database_names()

if 'ruboob' in dblist:
    print('数据库已存在')

5. Create a collection (there is no concept of data tables in MongoDB, collectively referred to as collections)

Collections in MongoDB are similar to tables in SQL, using database objects to create collections:

import pymongo

myclient=pymongo.MongoClient('mongodb://localhost:27107/')
mydb=myclient['runoob']

mycol=mydb['sites']

# 创建集合(数据表)后要再插入一个文档(记录),集合才会真正创建。

6. Determine whether the collection exists

import pymongo

myclient=pymongo.MongoClient('mongodb://localhost:27107/')
mydb=myclient['runoobdb']

collist=mydb.list_collection_names()

if 'sites' in collist:
    print('集合已存在!')

7. Add, delete, modify, and check operations

One, add data

Insert a single piece of data into the collection : call the interface insert_one() , and the parameter is in dictionary format.

import pymongo

myclient=pymongo.MongoClient('mongodb://localhost:27107/')
mydb=myclient['runoobdb']
mycol=mydb['sites']

mydict={'name':'RUNOOB','url':'www.baidu.com'}

x=mycol.insert_one(mydict)
print(x)

# 插入数据后得到返回的InsertOneResult对象,包含inserted_id,它是插入文档的id值。
print(x.inserted_id)

Insert multiple documents into the collection using the insert_many() interface, and the parameter is a list of dictionaries.

import pymongo

myclient=pymongo.MongoClient('mongodb://localhost:27107/')
mydb=myclient['runoobdb']
mycol=mydb['sites']

mylist = [
  { "name": "Taobao", "alexa": "100", "url": "https://www.taobao.com" },
  { "name": "QQ", "alexa": "101", "url": "https://www.qq.com" },
  { "name": "Facebook", "alexa": "10", "url": "https://www.facebook.com" },
  { "name": "知乎", "alexa": "103", "url": "https://www.zhihu.com" },
  { "name": "Github", "alexa": "109", "url": "https://www.github.com" }
]

x=mycol.insert_many(mylist)

#输出插入的所有文档对应的 _id 值
print(x.inserted_ids)

Insert multiple documents with specified _id

import pymongo

myclient=pymongo.MongoClient('mongodb://localhost:27107/')
mydb=myclient['runoobdb']
mycol=mydb['site2']

mylist = [
  { "_id": 1, "name": "RUNOOB", "cn_name": "菜鸟教程"},
  { "_id": 2, "name": "Google", "address": "Google 搜索"},
  { "_id": 3, "name": "Facebook", "address": "脸书"},
  { "_id": 4, "name": "Taobao", "address": "淘宝"},
  { "_id": 5, "name": "Zhihu", "address": "知乎"}
]

x=mycol.insert_many(mylist)

# 输出文档对应的  _id  值
print(x.inserted_ids)

Two, query data

Query a piece of data : Use the find_one() method to query a piece of data in the collection, such as querying the first piece of data in the sites document.

import pymongo
 
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["runoobdb"]
mycol = mydb["sites"]
 
x = mycol.find_one()
 
print(x)

# 输出结果
{'_id': ObjectId('5b23696ac315325f269f28d1'), 'name': 'RUNOOB', 'alexa': '10000',
 'url': 'https://www.runoob.com'}

Query all data in the collection : The find() method can query all the data in the collection, similar to the select * operation in SQL .

Such as:

import pymongo

myclient=pymongo.MongoClient('mongodb://localhost:27107/')
mydb=myclient['runoobdb']
mycol=mydb['sites']

for x in mycol.find():
    print(x)

# 输出结果
{'_id': ObjectId('5b23696ac315325f269f28d1'), 'name': 'RUNOOB', 'alexa': '10000', 'url': 'https://www.runoob.com'}
{'_id': ObjectId('5b2369cac315325f3698a1cf'), 'name': 'Google', 'alexa': '1', 'url': 'https://www.google.com'}
{'_id': ObjectId('5b236aa9c315325f5236bbb6'), 'name': 'Taobao', 'alexa': '100', 'url': 'https://www.taobao.com'}
{'_id': ObjectId('5b236aa9c315325f5236bbb7'), 'name': 'QQ', 'alexa': '101', 'url': 'https://www.qq.com'}
{'_id': ObjectId('5b236aa9c315325f5236bbb8'), 'name': 'Facebook', 'alexa': '10', 'url': 'https://www.facebook.com'}
{'_id': ObjectId('5b236aa9c315325f5236bbb9'), 'name': '知乎', 'alexa': '103', 'url': 'https://www.zhihu.com'}
{'_id': ObjectId('5b236aa9c315325f5236bbba'), 'name': 'Github', 'alexa': '109', 'url': 'https://www.github.com'}

Query the data of the specified field: still use the find() method, but set the field to be returned to 1 .

Such as:

import pymongo

myclient=pymongo.MongoClient('mongodb://localhost:27107/')
mydb=myclient['runoobdb']
mycol=mydb['sites']

for x in mycol.find({},{'_id':0,'name':1,'alexa':1})
    print(x)

# 输出结果
{'name': 'RUNOOB', 'alexa': '10000'}
{'name': 'Google', 'alexa': '1'}
{'name': 'Taobao', 'alexa': '100'}
{'name': 'QQ', 'alexa': '101'}
{'name': 'Facebook', 'alexa': '10'}
{'name': '知乎', 'alexa': '103'}
{'name': 'Github', 'alexa': '109'}

Note: Except for _id, you can specify both 0 and 1 in an object. If one field is 0, the others are all 1, and vice versa.

For example, except for the alexa field, everything else returns:

import pymongo

myclient=pymongo.MongoClient('mongodb://localhost:27107/')
mydb=myclient['runoobdb']
mycol=mydb['sites']

for x in mycol.find({},{'alexa':0})
    print(x)


# 输出结果
{'_id': ObjectId('5b23696ac315325f269f28d1'), 'name': 'RUNOOB', 'url': 'https://www.runoob.com'}
{'_id': ObjectId('5b2369cac315325f3698a1cf'), 'name': 'Google', 'url': 'https://www.google.com'}
{'_id': ObjectId('5b236aa9c315325f5236bbb6'), 'name': 'Taobao', 'url': 'https://www.taobao.com'}
{'_id': ObjectId('5b236aa9c315325f5236bbb7'), 'name': 'QQ', 'url': 'https://www.qq.com'}
{'_id': ObjectId('5b236aa9c315325f5236bbb8'), 'name': 'Facebook', 'url': 'https://www.facebook.com'}
{'_id': ObjectId('5b236aa9c315325f5236bbb9'), 'name': '知乎', 'url': 'https://www.zhihu.com'}
{'_id': ObjectId('5b236aa9c315325f5236bbba'), 'name': 'Github', 'url': 'https://www.github.com'}

Specify query conditions : set parameters in find() to filter data.

import pymongo

myclient=pymongo.MongoClient("mongdb://localhost:27107/')
mydb=myclient['runoobdb']
mycol=mydb['sites']

query={"name":"RUNOOB"}

result=mycol.find(query)

for x in resutl:
    print(x)

# 输出结果
{'_id': ObjectId('5b23696ac315325f269f28d1'), 'name': 'RUNOOB', 'alexa': '10000', 'url': 'https://www.runoob.com'}

Return the number of specified entries : use limit(), such as mycol.find().limit(3)

Regular expression query: If you read the data whose first letter is R in the name field, the regular expression modifier condition is {"$regex":"^R"}

query={'name':{'$regex':'^R'}}
result=mycol.find(query)

for x in result:
    print(x)

Three, modify the data

To modify a single piece of data , use the update_one()  interface to query the first matching data and modify it. For example, change the value of the alexa field from 10000 to 12345.

import pymongo
 
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["runoobdb"]
mycol = mydb["sites"]

myquery = { "alexa": "10000" }
newvalues = { "$set": { "alexa": "12345" } }
 
mycol.update_one(myquery, newvalues)
 
# 输出修改后的  "sites"  集合
for x in mycol.find():
  print(x)

To modify multiple data , use update_many(), such as finding the name field at the beginning of F, and modifying the found alexa field to 123:

import pymongo

myclient=pymongo.MongoClient('mongodb:localhost:27107/')
mydb=myclient['runoob']
mycol=mydb['sites']

myquery={'name':{'$regex':'^F'}}
newvalues={'$set':{'alexa':'123'}}

x=mycol.update_many(myquery,newvalues)
print(x.modified_count,'文档已修改')

Four, delete data

Delete a single piece of data , find the first matching object, and delete:

import pymongo

myclient=pymongo.MongoClient('mongodb:localhost/')
mydb=myclient['runoobdb']
mycol=mydb['sites']

myquery={'name':'Taobao'}

mycol.delete_one(myquery)

# 删除后输出
for  x in mycol.find():
    print(x)

To delete multiple documents , use delete_many() , use regular query, and delete, for example, delete documents starting with F in the name field:

import pymongo

myclient=pymongo.MongoClient('mongodb://localhost:27107/')
mydb=myclient['runoobdb']

mycol=mydb['sites']

myquery={'name':{'$regex':'^F'}}

x=mycol.find_many(mysquery)
print(x.delete_count,'个文档已删除')

To delete all documents in the collection , there is no need to specify fields, just use {} instead:

import pymongo

myclient=pymongo.MongoClient('mongodb://localhost:27107/')
mydb=myclient['runoobdb']
mycol=mydb['sites']

mycol.delete_many({})

print(x.deleted_count,'个文档已删除')

To delete the combination , use the drop() interface

import pymongo

myclient=pymongo.MongoClient('mongodb://localhost:27107/')
mydb=myclient['runoobdb']
mycol=mydb['sites']

mycol.drop()

Five, view the table

The operation method is similar to mysql,

# 切换数据库
use runoobdb;

# 查看所有数据表
show tables;

 

Guess you like

Origin blog.csdn.net/weixin_38664232/article/details/108416614