mongodb

MongoDB:
	引用了不存在的對象即建立改對象
	database	<->  Database
	table		<->  Collection
	字段		<->  Field
	row			<->  Document
	
1.MongoDB增刪改查:
	增:
		官方不推薦寫法:
		db.users.insert([{}]) 
		db.users.insert({})
		官方支持寫法:
		db.users.insertMany([{name:"金角大王八",age:"84"}])
		db.users.insertOne({name:"銀角大王八",age:"73"})
	
	查:
		db.users.find({age:73,name:"武大郎"})
		db.users.findOne({age:73})
		
	改:MongoDB修改器 $set $unset
		官方不推薦寫法:
		db.users.update({age:73},{$set:{age:74}})
		官方支持寫法:
		db.users.updateOne({age:73},{$set:{age:74}})
		db.users.updateMany({age:74},{$set:{age:73}})
		$set = dict["age"] = 73  # 修改字典的值
		$unset = del dict["age"]  # 刪除字典的鍵
	
	刪:
		官方不推薦寫法:
		db.users.remove({})
		官方支持寫法:
		db.users.deleteOne({age:"84"})
		db.users.deleteMany({age:"84"})
		
	
	2.MongoDB的數據類型
		首先咱們要先了解一下MongoDB中有什麼樣的數據類型:
		Object ID :Documents 自生成的 _id
		String: 字符串,必須是utf-8
		Boolean:布爾值,true 或者false (這裏有坑哦~在咱們大Python中 True False 首字母大寫)
		Integer:整數 (Int32 Int64 大家就知道有個Int就好了,通常咱們用Int32)
		Double:浮點數 (沒有float類型,全部小數都是Double)
		Arrays:數組或者列表,多個值存儲到一個鍵 (list哦,大Python中的List哦)
		Object:若是你學過Python的話,那麼這個概念特別好理解,就是Python中的字典,這個數據類型就是字典
		Null:空數據類型 , 一個特殊的概念,None Null
		Timestamp:時間戳
		Date:存儲當前日期或時間unix時間格式 (咱們通常不用這個Date類型,時間戳能夠秒殺一切時間類型)

		看着挺多的,可是真要是用的話,沒那麼複雜,很簡單的哦
		
	3.$關鍵字:
	修改器
		$set : 強制覆蓋
		$unset : 刪除字段
		$inc :引用自增 $inc:{age:-1} # -1是增長的數值,負數表示減
		
		[]:
		$push append(7) db.sss.updateOne({name:"AlexDSB"},{$push:{hobby_1:7}})  # 添加7到hobby_l 列表中,其中須要知足條件name = AlexDSB
		$pull remove(1) db.sss.updateOne({name:"AlexDSB"},{$pull:{hobby_1:1}})  # 刪除hobby_l列表中的1
		$pop  pop() db.sss.updateOne({name:"AlexDSB"},{$pop:{hobby_1:1/-1}})  # 1是從hobby_l 列表的尾部刪除一個數,-1是從hobby_l列表的頭部刪除一個數
	
	查詢關鍵:
		$or  $or:[{age:1},{name:2}]
		$all {u_list:{$all:[321,123]}}  # 查詢條件是必須含有321和123,能夠多含有別的值,可是不能少
		$in  {age:{$in:[10,15]}}
          $nin 不在範圍內 # where age=10 or age=15 or age=20 數學比較符: $lt {age:{$gt:10}} $lte $gt $gte $eq : $ne {age:{$ne:15}} # 不等於 4. $ 存放array的下標索引 {u_list:666,1},{hobby:2,2} {name:1,u_list:666},{$set:{"u_list.$":999}} Object: ({name:"AlexDSB","hobby.name":"我的計算機"},{$set:{"hobby.$.name":"PC"}}) 5.skip limit sort sort: sort({ age:1 / -1}) -1:倒序 1:正序 skip: skip(2) 跳過兩條 limit: limit(2) 選取兩條 1.sort > 2.skip > 3.limit 執行的前後順序,優先sort,其次skip,最後limit

    

     

Python中使用mongodb

import pymongo
from bson import ObjectId
mongo_cilent = pymongo.MongoClient(host="127.0.0.1",port=27017)
DB = mongo_cilent["day122"]

res = list(DB.users.find()) # <=100000
print(res)

import json
res = DB.users.find_one({"$or":[{"name":5},{"age":20}]}) # <=100000
res["_id"] = str(res["_id"])
res = json.dumps(res)
print(res)

# 增
res = DB.users.insert_one({"name":999})
print(res.inserted_id,type(res.inserted_id)) # Object 不能被JSON

res = DB.users.insert_many([{"name":"jwb"},{"name":"ywb"},{"name":"OldWB"}])
print(res.inserted_ids)

# 刪除
res = DB.users.delete_one({"name":"ywb"})
print(res.deleted_count)
res = DB.users.delete_many({"name":"jwb"})
print(res.deleted_count,dir(res))

# Update
res = DB.users.update_one({"name":"yinwang8"},{"$set":{"name":"ywb"}})
print(res.modified_count,dir(res))
#
res = DB.users.update_many({"name":"ywb"},{"$set":{"name":"YWB"}})
print(res.modified_count,dir(res))

DB.sss.update_one({"obj.k3":"v3"},{"$set":{"obj.k3":"vv3"}})
res = DB.sss.find_one({"obj.k3":"v3"})
res["obj"]["k3"] = "vv3"
DB.sss.update_one({"obj.k3":"v3"},{"$set":res})
hobby_list= [{"name":999,"year":1},
  {"name":666,"year":1},
  {"name":555,"year":1},
  {"name":888,"year":1},
  {"name":777,"year":1}]
 res = DB.sss.find_one({"_id":ObjectId("5bfe0708f7e06f13407ee6bd")})
 res["hobby"].extend(hobby_list)
 DB.sss.update_one({"_id":ObjectId("5bfe0708f7e06f13407ee6bd")},{"$set":res})

 res = DB.users.find({}).limit(2).skip(2).sort("name",pymongo.DESCENDING)
 print(list(res))

 res = DB.sss.find_one({})
 for index,i in enumerate(res["hobby_1"]):
     print(index)
     for index2,j in enumerate(i) :
         if j.get("name") == 1:
             print(index2)
             res["hobby_1"][index][index2]["name"]=10

 DB.sss.update_one({"_id":res["_id"]},{"$set":res})


  

save函數
1.能夠在文檔不存在的時候插入,存在的時候更新,只有一個參數文檔。
2.要是文檔含有"_id",會調用upsert。不然,會調用插入。
> db.a.find()
{ "_id" : ObjectId("50026affdeb4fa8d154f8572"), "desc" : "hello world1!", "num": 50,"sname" : "jk", "type" : "1", "uid" : "20120002" } 
> var o = db.a.findOne()
> o.num = 55
> db.a.save(o)
> db.a.find()
{ "_id" : ObjectId("50026affdeb4fa8d154f8572"), "desc" : "hello world1!", "num": 55,"sname" : "jk", "type" : "1", "uid" : "20120002" }
    
      
相關文章
相關標籤/搜索