mongodb是基于分布式文件存儲的nosql(非關系型)數(shù)據(jù)庫
雖說是nosqldb, but mongodb 其中的文檔可以是關系型的
在mongodb中, 表為集合, 里面的數(shù)據(jù)為文檔; 文檔本質就是一條調JSON數(shù)據(jù)
進入mongodb: mongo
退出mongodb: exit
庫操作
顯示庫: show dbs
選擇或者創(chuàng)建: use llsdb
# 不管該庫是否存在,都會use進入, 如何該庫不存在, use進去不存入數(shù)據(jù)退出時,該庫 不會被創(chuàng)建. 所以創(chuàng)建庫就use再寫入數(shù)據(jù).
查看所在庫: db
刪除庫: db.dropDatabase()
,要先use進入庫才刪除.
集合操作
顯示集合: show collections
創(chuàng)建集合: db.createCollection('llscol' [,options])
刪除集合: db.llscol.drop()
數(shù)據(jù)的CURD
插入數(shù)據(jù): db.llscol.insert({name: 'lls', age: 18})
插入多條數(shù)據(jù):
db.llscol.insert([ {name: 'lls1', age: 18}, {name: 'lls2', age: 20}])
查看數(shù)據(jù): db.llscol.find()
帶格式的數(shù)據(jù): db.llscol.find().pretty()
全文檔更新數(shù)據(jù): db.llscol.update({name: 'haha'}, {xx: 'yy'})
# {name: ‘hha'}是條件, 用于匹配項來更新.
指定字段更新 $set,{multi: true}: db.llscol.update({name: 'lls1'}, {$set: {name: 'xxx', age: 666}})
# 前面的{}為條件, 只會更新匹配到的第一個項.
更新多條 {multi: true}: db.llscol.update({name: 'lls1'}, {$set: {name: 'lls666'}}, {multi: true})
# 在全文檔匹配到對應項后更新每一條JSON中的對應的鍵值對.
刪除數(shù)據(jù): db.llscol.remove({name: 'lls1'})
# remove 所以包含{name: ‘lls1'}的json.
只刪除一條 {justOne: true}: db.llscol.remove({name: 'lls1'}, {justOne: true})
# 刪除匹配到的第一項.
python操作mongodb
import pymongoclient = pymongo.MongoClient('192.168.0.104', 27017) # 連接并建立client.db = client['llsdb'] # select database_name db = client.llsdbstu = db['student'] # select table_name stu = db.studentstu.insert_one({'name': 'lls'})stu.insert_many([ {'name1': 'lls1', 'age': 18}, {'name2': 'lls2', 'age': 20}, {'name3': 'lls3', 'age': 30}])stu.update_one({'name1': 'lls1'}, {'$set': {'age': 20}})stu.update_many({'name2': 'lls2'}, {'$set': {'age': 90}})print(stu.find_one({'name2': 'lls2'})) # 查詢無args的第一行,或匹配到的第一個行.content_find = stu.find({}) # 空字典表示查詢所有.print(content_find)for i in content_find: print(i)print(stu.delete_many({'name': 'lls'}).deleted_count)print(stu.delete_many({}).deleted_count)"""方法如下:insert_one, insert_many, update_one, update_many, delete_one, delete_many, find_one, find."""
本文分享Mongodb基本操作與Python連接并操作mongodb的基礎方法非常基礎但也是日常工作中的必知必會的知識點
新聞熱點
疑難解答