首先在下載頁面下載對應(yīng)版本的MongoDB,下面以windows平臺為例。
設(shè)置MongoDB服務(wù)
1.將MongoDB安裝在F:/mongodb,然后創(chuàng)建數(shù)據(jù)存放位置F:/mongodb/data/db
2.在F:/mongodb/data/下新建一個log文件夾,在該文件夾下創(chuàng)建mongodb.log文件
3.在 F:/mongodb下新建mongo.config,并添加以下內(nèi)容:
dbpath=F:\mongodb\data\db
logpath=F:\mongodb\data\log\mongodb.log
4.以管理員身份打開cmd,并進入F:/mongodb/bin,輸入以下命令:
mongod --config F:\mongodb\mongo.config --install --serviceName "MongoDB" --journal
5.執(zhí)行net start mongoDB命令即可開啟服務(wù)
6.為了方便,在系統(tǒng)變量的Path中添加MongoDB bin文件所在目錄F:/mongodb/bin,然后使用mongo命令進入數(shù)據(jù)庫
使用Python操作MongoDB數(shù)據(jù)庫
首先安裝相應(yīng)模塊。
pip install pymongo
下面以一個小demo介紹基本操作。
# -*- coding: utf-8 -*-
from pymongo import MongoClient
from datetime import datetime
from bson.objectid import ObjectId
class Test:
def __init__(self):
"""
連接MongoClient
由3種方法可以選擇,看使用情況
"""
# 簡寫
self.client = MongoClient()
# 指定端口和地址
# self.client = MongoClient('127.0.0.1', 27017)
# 使用URI
# self.client = MongoClient('mongodb://127.0.0.1:27017/')
# 選擇數(shù)據(jù)庫
self.db = self.client['test']
def add_one(self, title, number, created_time=datetime.now()):
"""
添加一條數(shù)據(jù)
需要注意的是Mongo中不需要事先建立表,插入數(shù)據(jù)的同時直接根據(jù)所傳入字典對象的內(nèi)容生成表
"""
# 創(chuàng)建一個字典對象
post = {
'title': title,
'number': number,
'created_time': created_time
}
# 指定將數(shù)據(jù)添加到blog下的post表
return self.db.blog.post.insert_one(post)
def find_by_id(self, post_id):
"""
通過ID查找數(shù)據(jù)
Mongo中自動生成的ID主鍵是ObjectId(id)的形式,所以在查詢的時候要遵循該格式
從bson.objectid導入ObjectId
"""
return self.db.blog.post.find_one({'_id': ObjectId(post_id)})
def update_number(self, post_id, number):
"""
更新一條數(shù)據(jù)
在update_one函數(shù)中,通過第一個參數(shù)查找更新對象,通過第二個參數(shù)對查找到的對象進行更新
下面語句的含義是對指定ID的數(shù)據(jù)的number字段加上一個number值,通過 $inc 實現(xiàn)
"""
return self.db.blog.post.update_one({'_id': ObjectId(post_id)}, {'$inc': {'number': number}})
def update_all_number(self, number):
"""
批量更新
update_many函數(shù)參數(shù)的作用同update_one
{} 表示沒有查找限制,更新全部的數(shù)據(jù)
"""
return self.db.blog.post.update_many({}, {'$inc': {'number': number}})
def delete_by_id(self, post_id):
"""
根據(jù)ID刪除,同樣注意id值的格式
"""
return self.db.blog.post.delete_one({'_id': ObjectId(post_id)})
MongoDB可視化工具
Robo 3T
在Tree Mode下查看數(shù)據(jù)

image.png
在Table Mode下查看數(shù)據(jù)

image.png
在Text Mode下查看數(shù)據(jù)

image.png