python mongodb数据库增删改查

地址,端口

数据库,集合,域。 

  1. 增insert

#!/usr/bin/python3

import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydb"]
mycol = mydb["col"]

mylist = [
    {"_id": 1, "name": "wjsou.com", "address": "文件搜索"},
    {"_id": 2, "name": "baidu.com", "address": "通用搜索"},
    {"_id": 3, "name": "bilibili.com", "address": "免费视频学习"},
    {"_id": 4, "name": "Taobao.com", "address": "淘宝购物赚钱"},
    {"_id": 5, "name": "sina.com", "address": "新浪生活"}
]

x = mycol.insert_many(mylist)

# 输出插入的所有文档对应的 _id 值
print(x.inserted_ids)

# x = mycol.find_one()
# print(x)
  1. 删delete

#!/usr/bin/python3

import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydb"]
mycol = mydb["col"]

myquery = {"name": {"$regex": "^s"}}

x = mycol.delete_many(myquery)

print(x.deleted_count, "个文档已删除")
  1. 改update

import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydb"]
mycol = mydb["col"]

myquery = {"name": {"$regex": "^w"}}
newvalues = {"$set": {"chenhao": "29"}}

x = mycol.update_many(myquery, newvalues)

print(x.modified_count, "文档已修改")
  1. 查find

#!/usr/bin/python3
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydb"]
mycol = mydb["col"]
myquery = {"name": {"$regex": ".*?o.*?"}}
mydoc = mycol.find(myquery)
for x in mydoc:
    print(x)

 

你可能感兴趣的:(日志)