2019-12-13 python 操作mongodb

直接py代码解析

一. 插入一个文档方式

#导入模块
import pymongo
#链接本地mongodb server
myclient=pymongo.MongoClient("mongodb://localhost:27017/")
#创建数据库
mydb=myclient["runooddb"]
#创建集合
mycol=mydb["sites1"]
#编辑一个文档集合
mydict = { "name": "Google", "alexa": "1", "url": "https://www.google.com" }
#插入一个文档集合
x = mycol.insert_one(mydict)
print(x.inserted_id)
  1. 使用mongo.exe find指令:


  2. print(x.inserted_id)
5df38465caee36865e2075a0
  1. 可视化工具显示:


    image.png

插入多个文档,以集合的方式

import pymongo
myclient=pymongo.MongoClient("mongodb://localhost:27017/")
mydb=myclient["runooddb"]
mycol=mydb["sites"]
mylist = [
  { "name": "Taobao", "alexa": "100", "url": "https://www.taobao.com" },
  { "name": "QQ", "alexa": "101", "url": "https://www.qq.com" },
  { "name": "Facebook", "alexa": "10", "url": "https://www.facebook.com" },
  { "name": "知乎", "alexa": "103", "url": "https://www.zhihu.com" },
  { "name": "Github", "alexa": "109", "url": "https://www.github.com" }
]
x=mycol.insert_many(mylist)
print(x.inserted_ids)
image.png
image.png

你可能感兴趣的:(2019-12-13 python 操作mongodb)