1、簡(jiǎn)介
MongoDB是一個(gè)文檔數(shù)據(jù)庫(kù),旨在簡(jiǎn)化應(yīng)用程序 開發(fā)和擴(kuò)展。
官網(wǎng)地址:
https://www.mongodb.com/
MongoDB 是一個(gè)基于分布式文件存儲(chǔ)的數(shù)據(jù)庫(kù)。由 C++ 語(yǔ)言編寫。旨在為 WEB 應(yīng)用提供可擴(kuò)展的高性能數(shù)據(jù)存儲(chǔ)解決方案。
MongoDB 是一個(gè)介于關(guān)系數(shù)據(jù)庫(kù)和非關(guān)系數(shù)據(jù)庫(kù)之間的產(chǎn)品,是非關(guān)系數(shù)據(jù)庫(kù)當(dāng)中功能最豐富,最像關(guān)系數(shù)據(jù)庫(kù)的。
MongoDB 是由C++語(yǔ)言編寫的,是一個(gè)基于分布式文件存儲(chǔ)的開源數(shù)據(jù)庫(kù)系統(tǒng)。
MongoDB 旨在為WEB應(yīng)用提供可擴(kuò)展的高性能數(shù)據(jù)存儲(chǔ)解決方案。在高負(fù)載的情況下,添加更多的節(jié)點(diǎn),可以保證服務(wù)器性能。
MongoDB 將數(shù)據(jù)存儲(chǔ)為一個(gè)文檔,數(shù)據(jù)結(jié)構(gòu)由鍵值(key=>value)對(duì)組成。MongoDB 文檔類似于 JSON 對(duì)象。字段值可以包含其他文檔,數(shù)組及文檔數(shù)組。
MongoDB 數(shù)據(jù)庫(kù)主要用于海量存儲(chǔ),常被用在數(shù)據(jù)采集項(xiàng)目中。數(shù)據(jù)存儲(chǔ)不需要固定模式,不需要多余操作就可以橫向擴(kuò)展,低成本,沒有復(fù)雜的關(guān)系,安裝簡(jiǎn)單,支持各種編程語(yǔ)言等。
2、下載和安裝
2.1 平臺(tái)支持
MongoDB 6.0 Community Edition 支持以下 64 位版本的 Windowsx86_64。
MongoDB僅支持這些平臺(tái)的64位版本。
- Windows Server 2019
- Windows 10 / Windows Server 2016
2.2 MongoDB Community Server
MongoDB有兩個(gè)服務(wù)器版本: 社區(qū)版和商業(yè)版。
其中社區(qū)版又分為如下幾種:
- 在 Linux 上安裝
安裝 MongoDB 社區(qū)版和所需的依賴項(xiàng) Linux。- Install MongoDB Community Edition on Red Hat or CentOS
- Install MongoDB Community Edition on Ubuntu
- Install MongoDB Community Edition on Debian
- Install MongoDB Community Edition on SUSE
- Install MongoDB Community Edition on Amazon Linux
- 在 macOS 上安裝
從MongoDB在macOS系統(tǒng)上安裝MongoDB社區(qū)版 檔案。- Install MongoDB Community Edition on macOS
- 在Windows上安裝
在Windows系統(tǒng)上安裝MongoDB社區(qū)版,并 (可選)將MongoDB作為Windows服務(wù)啟動(dòng)。- Install MongoDB Community Edition on Windows
- 使用 Docker 安裝
安裝 MongoDB Community Docker 容器。- Install MongoDB Community with Docker
這里以Windows為例說(shuō)明。
直接運(yùn)行安裝程序mongodb-windows-x86_64-6.0.6-signed.msi,最開始界面如下:
4.0之后,可以再M(fèi)ongoDB安裝期間將MongoDB配置為服務(wù)。把MongoDB配置為Windows服務(wù)。勾選Install MongoD as a Service(默認(rèn)勾選),如果不勾選就只安裝二進(jìn)制文件,不作為服務(wù)。 然后選擇 Run Service as Network Service user(以網(wǎng)絡(luò)服務(wù)用戶的身份運(yùn)行)(默認(rèn))
點(diǎn)擊next后把 Install MongoDB Compass勾選給去掉。一般建議單獨(dú)下載安裝。最后安裝完成如下:
按 Ctrl + Shfit + Esc,打開任務(wù)管理器,切換到服務(wù)選項(xiàng)卡,下拉找到 MongoDB 服務(wù)。在這里可以觀察到 MongoDB 的狀態(tài),默認(rèn)是自動(dòng)啟動(dòng),即開機(jī)自啟。
或者打開瀏覽器訪問 :
http://localhost:27017
顯示如上信息,說(shuō)明MongoDB服務(wù)啟動(dòng)成功。
# 開始MongoDB服務(wù)
net start mongodb
# 關(guān)閉MongoDB服務(wù)
net stop mongodb
您可以配置mongod和mongos實(shí)例位于 使用配置文件啟動(dòng)。配置文件包含 等效于mongod和mongos命令行選項(xiàng)。
mongod --config <configuration file>
mongod --config /etc/mongod.conf
mongos --config /etc/mongos.conf
mongod -f /etc/mongod.conf
mongos -f /etc/mongos.conf
以下是一個(gè)示例配置文件:
systemLog:
destination: file
path: "/var/log/mongodb/mongod.log"
logAppend: true
storage:
journal:
enabled: true
processManagement:
fork: true
net:
bindIp: 127.0.0.1
port: 27017
setParameter:
enableLocalhostAuthBypass: false
...
YAML 不支持縮進(jìn)制表符:請(qǐng)改用空格。
2.3 MongoDB Shell
打開MongoDB 的安裝目錄,默認(rèn)是 C:/Program Files/MongoDB/Server/6.0
MongoDB 目錄如下:
其中,bin 是 MongoDB 提供的可執(zhí)行程序的目錄,data 是數(shù)據(jù)存儲(chǔ)的目錄,log 是日志存儲(chǔ)的目錄。后兩者在過(guò)去都需要開發(fā)者手動(dòng)創(chuàng)建?,F(xiàn)在安裝程序會(huì)自動(dòng)創(chuàng)建。
現(xiàn)在查看bin 目錄:
其中,mongod.exe 用來(lái)啟動(dòng) MongoDB 服務(wù),mongos.exe 用來(lái)管理分片集群。
在 MongDB 6 以前,這個(gè)目錄下會(huì)有很多可執(zhí)行程序,比如最常用的 mongo.exe,它用來(lái)連接到 MongoDB 服務(wù),是一個(gè) shell 環(huán)境的客戶端工具。但是現(xiàn)在需要單獨(dú)進(jìn)行安裝。
MongoDB Shell是連接(和使用)MongoDB的最快方式。使用這個(gè)可擴(kuò)展的現(xiàn)代命令行界面輕松查詢數(shù)據(jù)、配置設(shè)置和執(zhí)行其他操作 - 充滿了語(yǔ)法突出顯示、智能自動(dòng)完成、上下文幫助和錯(cuò)誤消息。
注意:MongoDB Shell是一個(gè)開源(Apache 2.0),獨(dú)立于MongoDB服務(wù)器開發(fā)的獨(dú)立產(chǎn)品。
https://www.mongodb.com/try/download/shell
mongosh-1.10.1-win32-x64.zip
解壓之后,打開bin文件夾如下:
將上面兩個(gè)文件復(fù)制到MongoDB 服務(wù)器安裝文件夾的bin里面:
如果使用 Shell 命令的形式打開 MongoDB,最好先配置環(huán)境變量。
將上面的MongoDB服務(wù)器的bin文件夾路徑添加到 Path 變量里面。
之后就可以在任意路徑下使用 mongosh、mongod 等命令了。
- 連接mongodb服務(wù)器
打開命令行工具,執(zhí)行 mongosh.exe ,默認(rèn)會(huì)連接 mongodb://localhost:27017 的 MongoDB 服務(wù):
mongosh
# or
mongosh --port 27017
- 查看mongodb所有的數(shù)據(jù)庫(kù):
show databases
# or
show dbs
2.4 MongoDB Compass
使用Compass(MongoDB的GUI)輕松探索和操作數(shù)據(jù)庫(kù)。Compass 直觀而靈活,提供詳細(xì)的模式可視化、實(shí)時(shí)性能指標(biāo)、復(fù)雜的查詢功能等等。
請(qǐng)注意,MongoDB Compass有三個(gè)版本:具有所有功能的完整版本,沒有寫入或刪除功能的只讀版本,以及唯一網(wǎng)絡(luò)連接與MongoDB實(shí)例的隔離版本。
https://www.mongodb.com/try/download/compass
2.5 pymongo庫(kù)
python -m pip install pymongo
# or
python -m pip install pymongo==3.11
# or
python -m pip install --upgrade pymongo
3、概念
Mongo中的一些概念:
SQL術(shù)語(yǔ)/概念 | MongoDB術(shù)語(yǔ)/概念 | 解釋/說(shuō)明 |
---|---|---|
database | database | 數(shù)據(jù)庫(kù) |
table | collection | 數(shù)據(jù)庫(kù)表/集合 |
row | document | 數(shù)據(jù)記錄行/文檔 |
column | field | 數(shù)據(jù)字段/域 |
index | index | 索引 |
table joins | 表連接,MongoDB不支持 | |
primary key | primary key | 主鍵,MongoDB自動(dòng)將_id字段設(shè)置為主鍵 |
3.1 數(shù)據(jù)庫(kù)
一個(gè)mongodb中可以建立多個(gè)數(shù)據(jù)庫(kù)。
MongoDB的默認(rèn)數(shù)據(jù)庫(kù)為"db",該數(shù)據(jù)庫(kù)存儲(chǔ)在data目錄中。
MongoDB的單個(gè)實(shí)例可以容納多個(gè)獨(dú)立的數(shù)據(jù)庫(kù),每一個(gè)都有自己的集合和權(quán)限,不同的數(shù)據(jù)庫(kù)也放置在不同的文件中。
- 命令:show dbs
命令可以顯示所有數(shù)據(jù)的列表。 - 命令:db
命令可以顯示當(dāng)前數(shù)據(jù)庫(kù)對(duì)象或集合。 - 命令:use
可以連接到一個(gè)指定的數(shù)據(jù)庫(kù)。如果數(shù)據(jù)庫(kù)不存在,則創(chuàng)建數(shù)據(jù)庫(kù),否則切換到指定數(shù)據(jù)庫(kù)。
數(shù)據(jù)庫(kù)名可以是滿足以下條件的任意UTF-8字符串:
不能是空字符串("")。
不得含有' '(空格)、.、$、/、\和\0 (空字符)。
應(yīng)全部小寫。
最多64字節(jié)。
特殊作用的數(shù)據(jù)庫(kù):
admin: 從權(quán)限的角度來(lái)看,這是"root"數(shù)據(jù)庫(kù)。要是將一個(gè)用戶添加到這個(gè)數(shù)據(jù)庫(kù),這個(gè)用戶自動(dòng)繼承所有數(shù)據(jù)庫(kù)的權(quán)限。一些特定的服務(wù)器端命令也只能從這個(gè)數(shù)據(jù)庫(kù)運(yùn)行,比如列出所有的數(shù)據(jù)庫(kù)或者關(guān)閉服務(wù)器。
local: 這個(gè)數(shù)據(jù)永遠(yuǎn)不會(huì)被復(fù)制,可以用來(lái)存儲(chǔ)限于本地單臺(tái)服務(wù)器的任意集合
config: 當(dāng)Mongo用于分片設(shè)置時(shí),config數(shù)據(jù)庫(kù)在內(nèi)部使用,用于保存分片的相關(guān)信息。
- 添加用戶名和密碼
設(shè)置超級(jí)管理員賬號(hào)和密碼:
use admin
db.createUser({
user: 'admin', // 用戶名(自定義)
pwd: '123456', // 密碼(自定義)
roles:[{
role: 'root', // 使用超級(jí)用戶角色
db: 'admin' // 指定數(shù)據(jù)庫(kù)
}]
})
找到MongoDB安裝目錄下的bin目錄中的mongod.cfg文件,開啟權(quán)限驗(yàn)證功能:
security:
authorization: enabled
重啟MongoDB服務(wù)。連接數(shù)據(jù)庫(kù),并登錄超級(jí)管理員賬號(hào)。
除了設(shè)置超級(jí)管理員賬號(hào)以外,還可以為每個(gè)數(shù)據(jù)庫(kù)單獨(dú)設(shè)置賬號(hào):
# 為自定義的數(shù)據(jù)庫(kù)myMongoDB創(chuàng)建了一個(gè)用戶hello,它具有對(duì)這個(gè)數(shù)據(jù)庫(kù)的讀寫權(quán)限。
use myMongoDB // 跳轉(zhuǎn)到需要添加用戶的數(shù)據(jù)庫(kù)
db.createUser({
user: 'hello', // 用戶名
pwd: '123456', // 密碼
roles:[{
role: 'readWrite', // 讀寫權(quán)限角色
db: 'myMongoDB' // 數(shù)據(jù)庫(kù)名
}]
})
角色描述 | 角色標(biāo)識(shí) |
---|---|
數(shù)據(jù)庫(kù)用戶角色 | read、readWrite |
數(shù)據(jù)庫(kù)管理角色 | dbAdmin、dbOwner、userAdmin |
集群管理角色 | clusterAdmin、clusterManager、clusterMonitor、hostManager |
備份恢復(fù)角色 | backup、restore |
所有數(shù)據(jù)庫(kù)角色 | readAnyDatabase、readWriteAnyDatabase、userAdminAnyDatabase、 dbAdminAnyDatabase |
超級(jí)用戶角色 | root |
- 命令:db.help()
Display help for database methods.
db.help()
-
命令:db.collection.help()
Display help on collection methods. The can be the name of an existing collection or a non-existing collection. -
命令:help
Display help. -
命令:show collections
Display a list of all collections for current database. -
命令:show dbs
Display a list of all databases on the server. -
命令:show tables
Display a list of collections in the current database. See show collections. -
命令:show users
Display a list of users for current database.
3.2 文檔(Document)
文檔是一組鍵值(key-value)對(duì)(即 BSON)。MongoDB 的文檔不需要設(shè)置相同的字段,并且相同的字段不需要相同的數(shù)據(jù)類型,這與關(guān)系型數(shù)據(jù)庫(kù)有很大的區(qū)別,也是 MongoDB 非常突出的特點(diǎn)。
一個(gè)簡(jiǎn)單的文檔例子如下:
MongoDB中的記錄是一個(gè)文檔,它是一個(gè)數(shù)據(jù)結(jié)構(gòu)組成 字段和值對(duì)。MongoDB文檔類似于JSON。 對(duì)象。字段的值可能包括其他文檔、數(shù)組、 和文檔數(shù)組。
RDBMS | MongoDB |
---|---|
數(shù)據(jù)庫(kù) | 數(shù)據(jù)庫(kù) |
表格 | 集合 |
行 | 文檔 |
列 | 字段 |
表聯(lián)合 | 嵌入文檔 |
主鍵 | 主鍵 (MongoDB 提供了 key 為 _id ) |
- 創(chuàng)建一個(gè)新數(shù)據(jù)庫(kù)和集合
use myNewDatabase
db.myCollection.insertOne( { x: 1 } );
- 添加一個(gè)Document
db.collection.insertOne()
use sample_mflix
db.movies.insertOne(
{
title: "The Favourite",
genres: [ "Drama", "History" ],
runtime: 121,
rated: "R",
year: 2018,
directors: [ "Yorgos Lanthimos" ],
cast: [ "Olivia Colman", "Emma Stone", "Rachel Weisz" ],
type: "movie"
}
)
#插入一條數(shù)據(jù):
db.stu.insert({name:'zhangsan','age':20});
#插入一條數(shù)據(jù),指定主鍵:
db.stu.insert({_id:3,'name':'lisi','age':28});
#增加多條數(shù)據(jù):
db.stu.insert(
[{name:'wangyi','age':18},{'name':'sunwu','age':25}])
- 添加多個(gè)Documents
db.collection.insertMany()
use sample_mflix
db.movies.insertMany([
{
title: "Jurassic World: Fallen Kingdom",
genres: [ "Action", "Sci-Fi" ],
runtime: 130,
rated: "PG-13",
year: 2018,
directors: [ "J. A. Bayona" ],
cast: [ "Chris Pratt", "Bryce Dallas Howard", "Rafe Spall" ],
type: "movie"
},
{
title: "Tag",
genres: [ "Comedy", "Action" ],
runtime: 105,
rated: "R",
year: 2018,
directors: [ "Jeff Tomsic" ],
cast: [ "Annabelle Wallis", "Jeremy Renner", "Jon Hamm" ],
type: "movie"
}
])
- 讀取一個(gè)Collection所有的Documents
db.collection.find()
use sample_mflix
db.movies.find()
- 指定相等條件讀取Documents
use sample_mflix
db.movies.find( { "title": "Titanic" } )
- 指定操作符條件讀取Documents
use sample_mflix
db.movies.find( { rated: { $in: [ "PG", "PG-13" ] } } )
- 指定與或邏輯條件讀取Documents
use sample_mflix
db.movies.find( { countries: "Mexico", "imdb.rating": { $gte: 7 } } )
- 更新Documents
db.collection.updateOne().
db.collection.updateMany().
db.collection.replaceOne().
use sample_mflix
db.movies.updateOne( { title: "Twilight" },
{
$set: {
plot: "A teenage girl risks everything–including her life–when she falls in love with a vampire."
},
$currentDate: { lastUpdated: true }
})
- 刪除Documents
db.collection.deleteMany()
db.collection.deleteOne()
use sample_mflix
db.movies.deleteMany({})
db.movies.deleteMany( { title: "Titanic" } )
db.movies.deleteOne( { cast: "Brad Pitt" } )
3.3 集合(Collection)
集合就是 MongoDB 文檔組,類似于 RDBMS 中的表格。
集合存在于數(shù)據(jù)庫(kù)中,集合沒有固定的結(jié)構(gòu),這意味著你在對(duì)集合可以插入不同格式和類型的數(shù)據(jù),但通常情況下我們插入集合的數(shù)據(jù)都會(huì)有一定的關(guān)聯(lián)性。
當(dāng)?shù)谝粋€(gè)文檔插入時(shí),集合就會(huì)被創(chuàng)建。
MongoDB將文檔存儲(chǔ)在集合。集合類似于關(guān)系數(shù)據(jù)庫(kù)中的表。
3.4 元數(shù)據(jù)
數(shù)據(jù)庫(kù)的信息是存儲(chǔ)在集合中。它們使用了系統(tǒng)的命名空間:
dbname.system.*
在MongoDB數(shù)據(jù)庫(kù)中名字空間 .system.* 是包含多種系統(tǒng)信息的特殊集合(Collection)。
3.5 數(shù)據(jù)類型
下表為MongoDB中常用的幾種數(shù)據(jù)類型。
數(shù)據(jù)類型 | 描述 |
---|---|
String | 字符串。存儲(chǔ)數(shù)據(jù)常用的數(shù)據(jù)類型。在 MongoDB 中,UTF-8 編碼的字符串才是合法的。 |
Integer | 整型數(shù)值。用于存儲(chǔ)數(shù)值。根據(jù)你所采用的服務(wù)器,可分為 32 位或 64 位。 |
Boolean | 布爾值。用于存儲(chǔ)布爾值(真/假)。 |
Double | 雙精度浮點(diǎn)值。用于存儲(chǔ)浮點(diǎn)值。 |
Min/Max keys | 將一個(gè)值與 BSON(二進(jìn)制的 JSON)元素的最低值和最高值相對(duì)比。 |
Array | 用于將數(shù)組或列表或多個(gè)值存儲(chǔ)為一個(gè)鍵。 |
Timestamp | 時(shí)間戳。記錄文檔修改或添加的具體時(shí)間。 |
Object | 用于內(nèi)嵌文檔。 |
Null | 用于創(chuàng)建空值。 |
Symbol | 符號(hào)。該數(shù)據(jù)類型基本上等同于字符串類型,但不同的是,它一般用于采用特殊符號(hào)類型的語(yǔ)言。 |
Date | 日期時(shí)間。用 UNIX 時(shí)間格式來(lái)存儲(chǔ)當(dāng)前日期或時(shí)間。你可以指定自己的日期時(shí)間:創(chuàng)建 Date 對(duì)象,傳入年月日信息。 |
Object ID | 對(duì)象 ID。用于創(chuàng)建文檔的 ID。 |
Binary Data | 二進(jìn)制數(shù)據(jù)。用于存儲(chǔ)二進(jìn)制數(shù)據(jù)。 |
Code | 代碼類型。用于在文檔中存儲(chǔ) JavaScript 代碼。 |
Regular expression | 正則表達(dá)式類型。用于存儲(chǔ)正則表達(dá)式。 |
4、Python代碼測(cè)試
4.1 連接數(shù)據(jù)庫(kù)
mongodb://localhost
mongodb://localhost:port
mongodb://sysop:moon@localhost
import pymongo
# myclient = pymongo.MongoClient()
# myclient = pymongo.MongoClient("mongodb://localhost:27017")
# myclient = pymongo.MongoClient('mongodb://admin:123456@localhost:27017/?authSource=admin')
myclient = pymongo.MongoClient('localhost',27017)
print(myclient.list_database_names())
import pymongo
myclient = pymongo.MongoClient('localhost', 27017)
db = mongo_client.admin
db.authenticate('用戶名', '密碼')
4.2 指定數(shù)據(jù)庫(kù)和集合
#獲取數(shù)據(jù)庫(kù)
db = client.test_database
# or
db = client["test-database"]
#指定集合
collection = db.test_collection
# or
collection = db["test-collection"]
4.3 插入數(shù)據(jù)
#增加一條
stu1={'id':'001','name':'zhangsan','age':10}
result = collection.insert_one(stu1)
#增加多條
stu2={'id':'002','name':'lisi','age':15}
stu3={'id':'003','name':'wangwu','age':20}
result = collection.insert_many([stu2,stu3])
import datetime
post = {
"author": "Mike",
"text": "My first blog post!",
"tags": ["mongodb", "python", "pymongo"],
"date": datetime.datetime.now(tz=datetime.timezone.utc),
}
posts = db.posts
post_id = posts.insert_one(post).inserted_id
db.list_collection_names()
import pprint
pprint.pprint(posts.find_one())
pprint.pprint(posts.find_one({"author": "Mike"}))
pprint.pprint(posts.find_one({"author": "Eliot"}))
pprint.pprint(posts.find_one({"_id": post_id}))
文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-773407.html
# Bulk Inserts
new_posts = [
{
"author": "Mike",
"text": "Another post!",
"tags": ["bulk", "insert"],
"date": datetime.datetime(2009, 11, 12, 11, 14),
},
{
"author": "Eliot",
"title": "MongoDB is fun",
"text": "and pretty easy too!",
"date": datetime.datetime(2009, 11, 10, 10, 45),
},
]
result = posts.insert_many(new_posts)
result.inserted_ids
# Querying for More Than One Document
for post in posts.find():
pprint.pprint(post)
# Counting
posts.count_documents({})
posts.count_documents({"author": "Mike"})
# Range Queries
d = datetime.datetime(2009, 11, 12, 12)
for post in posts.find({"date": {"$lt": d}}).sort("author"):
pprint.pprint(post)
from pymongo import MongoClient
# Replace the uri string with your MongoDB deployment's connection string.
uri = "mongodb://localhost:27017"
client = MongoClient(uri)
# database and collection code goes here
db = client.sample_guides
coll = db.comets
coll.drop()
# insert code goes here
docs = [
{"name": "Halley's Comet", "officialName": "1P/Halley", "orbitalPeriod": 75, "radius": 3.4175, "mass": 2.2e14},
{"name": "Wild2", "officialName": "81P/Wild", "orbitalPeriod": 6.41, "radius": 1.5534, "mass": 2.3e13},
{"name": "Comet Hyakutake", "officialName": "C/1996 B2", "orbitalPeriod": 17000, "radius": 0.77671, "mass": 8.8e12},
]
result = coll.insert_many(docs)
# display the results of your operation
print(result.inserted_ids)
# Close the connection to MongoDB when you're done.
client.close()
4.4 刪除數(shù)據(jù)
#可以直接使用remove方法刪除指定的數(shù)據(jù)
result = collection.remove({'name': 'zhangsan'})
#使用delete_one()刪除一條數(shù)據(jù)
result = collection.delete_one({"name":"zhangsan"})
#delete_many()刪除多條數(shù)據(jù)
result = collection.delete_many({"age":{'$lt':20}})
from pymongo import MongoClient
# Replace the uri string with your MongoDB deployment's connection string.
uri = "mongodb://localhost:27017"
client = MongoClient(uri)
# database and collection code goes here
db = client.sample_guides
coll = db.comets
# delete code goes here
doc = {
"orbitalPeriod": {
"$gt": 5,
"$lt": 85
}
}
result = coll.delete_many(doc)
# amount deleted code goes here
print("Number of documents deleted: ", result.deleted_count)
# Close the connection to MongoDB when you're done.
client.close()
4.5 修改數(shù)據(jù)
#update_one,第 2 個(gè)參數(shù)需要使用$類型操作符作為字典的鍵名
#姓名為zhangsan的記錄,age修改為22
condition = {'name': 'zhangsan'}
res = collection.find_one(condition)
res['age'] = 22
result = collection.update_one(condition, {'$set': res})
print(result) #返回結(jié)果是UpdateResult類型
print(result.matched_count,result.modified_count) #獲得匹配的數(shù)據(jù)條數(shù)1、影響的數(shù)據(jù)條數(shù)1
#update_many,所有年齡為15的name修改為xixi
condition = {'age': 15}
res = collection.find_one(condition)
res['age'] = 30
result = collection.update_many(condition, {'$set':{'name':'xixi'}})
print(result) #返回結(jié)果是UpdateResult類型
print(result.matched_count,result.modified_count) #獲得匹配的數(shù)據(jù)條數(shù)3、影響的數(shù)據(jù)條數(shù)3
from pymongo import MongoClient
# Replace the uri string with your MongoDB deployment's connection string.
uri = "mongodb://localhost:27017"
client = MongoClient(uri)
# database and collection code goes here
db = client.sample_guides
coll = db.comets
# update code goes here
doc = {"$mul": {"radius": 1.60934}}
result = coll.update_many({}, doc)
# display the results of your operation
print("Number of documents updated: ", result.modified_count)
# Close the connection to MongoDB when you're done.
client.close()
4.6 查詢數(shù)據(jù)
rets = collection.find({"age":20}),
for ret in rets:
print(ret)
# 查詢結(jié)果有多少條數(shù)據(jù)
count = collection.find().count()
# 查詢結(jié)果按年齡升序排序
results = collection.find().sort('age', pymongo.ASCENDING)
print([result['age'] for result in results])
ret =collection.find_one({'name': 'zhangsan'})
from pymongo import MongoClient
# Replace the uri string with your MongoDB deployment's connection string.
uri = "mongodb://localhost:27017"
client = MongoClient(uri)
# database and collection code goes here
db = client.sample_guides
coll = db.planets
# find code goes here
cursor = coll.find({"hasRings": True})
# iterate code goes here
for doc in cursor:
print(doc)
# find code goes here
cursor = coll.find({"surfaceTemperatureC.mean": {"$lt": 15}})
for doc in cursor:
print(doc)
# Close the connection to MongoDB when you're done.
client.close()
結(jié)語(yǔ)
如果您覺得該方法或代碼有一點(diǎn)點(diǎn)用處,可以給作者點(diǎn)個(gè)贊,或打賞杯咖啡;
╮( ̄▽ ̄)╭如果您感覺方法或代碼不咋地
//(ㄒoㄒ)//,就在評(píng)論處留言,作者繼續(xù)改進(jìn);
o_O???如果您需要相關(guān)功能的代碼定制化開發(fā),可以留言私信作者;
(????)感謝各位大佬童鞋們的支持!
( ′ ▽′ )? ( ′ ▽′)っ?。?!文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-773407.html
到了這里,關(guān)于【小沐學(xué)數(shù)據(jù)庫(kù)】MongoDB下載、安裝和入門(Python)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!