MongoDB 基本操作增删改查

import pymongo

mongo_client = pymongo.MongoClient(host="127.0.0.1",port=27017)

DB = mongo_client["users"]

1.查询
res = list(DB.school.find())
res = DB.school.find_one({"class_name":"16"},{"_id":0,"student":1})
res = DB.school.find_one({"class_name":"16"})
res = DB.school.find_one({"student.name":"哈哈"})
res = DB.school.find_one({'$or':[{"class_name":"S16"},{"school_name":"清华"}]})
res = DB.school.find_one({"userlist":{"$all":[3,4,2]}})
print(res)
res["_id"] = str(res.get("_id"))
import json
a = json.dumps(res)
print(a)

2.增加数据
res = DB.school.insert_one({"name":1})
print(res,res.inserted_id,type(res.inserted_id))
res = DB.school.insert_many([{"name":3},{"name":4},{"name":5}])
print(res,res.inserted_ids)
奇葩数据
res = DB.oldboy.insert_one({"user_list":[{"hobby":["抽烟","喝酒"]},{"hobby":[{"name":"car","type":"SUV"},{"name":"motor","type":"BMW"}]}]})


3.修改数据
$ 存储 array 符合条件元素的下标索引
from bson import ObjectId
res = DB.school.update_one({"_id":ObjectId("5c7e280ed0df65358812ccab")},{"$push":{"userlist":888}})
res = DB.school.update_one({"userlist":888},{"$set":{"userlist.$":666}})
res = DB.school.update_one({"userlist":666},{"$set":{"userlist.0":888}})
print(res,res.modified_count)
"""
{
	"_id" : ObjectId("5c7e3fcbd3620e1130463178"),
	"user_list" : [
		{
		"hobby" : [
			"抽烟",
			"喝酒"
		]
	},
		{
		"hobby" : [
			{
			"name" : "car",
			"type" : "SUV"
		},
			{
			"name" : "motor",
			"type" : "BMW"
		}
		]
	}
	]
}
"""
res = DB.oldboy.find_one({})
print(res)
for index,item in enumerate(res.get("user_list")):
    for hobby,hobby_item in enumerate(item.get("hobby")):
        if type(hobby_item) == dict:
            if hobby_item.get("name") == "motor":
                res["user_list"][index]["hobby"][hobby]["type"] = "Suzuki"

DB.oldboy.update_one({"_id":res.get("_id")},{"$set":res})

4.删除
from bson import ObjectId
res = DB.oldboy.delete_one({'_id': ObjectId('5c7e3fcbd3620e1130463178')})
print(res,dir(res),res.deleted_count)


选取 跳过 排序
res = list(DB.school.find().limit(5).skip(5))
print(res,len(res))

排序
res = list(DB.school.find().limit(5).skip(5).sort("_id",pymongo.ASCENDING))
res = list(DB.school.find().limit(5).skip(5).sort("_id",pymongo.DESCENDING))
print(res,len(res))

  

posted @ 2019-03-06 21:35  冒蓝火的加特林哒哒哒  阅读(199)  评论(0编辑  收藏  举报