#! /usr/bin/env python3
# -*- coding:utf-8 -*-
Author : MaYi
Date : 2019-12-25
Name : test01
Software : PyCharm
Note : 应用pymongo模块操作MongoDB数据库
导入模块
import pymongo
连接数据库,27017是默认端口
client = pymongo.MongoClient("localhost", 27017)
获取数据库
db = client.students
打印数据集合名称列表
print(db.collection_names)
获取数据集合
res = db.students.find()
print(res)
for item in res:
遍历数据
print(item)
wangwu = {"name": "Wangwu", "age": 20, "sex": "male"}
插入一条记录
db.students.insert(wangwu)
for item in db.students.find({"name": "Wangwu"}):
指定查询条件
print(item)
获取一条记录
print(db.students.find_one())
print(db.students.find_one({"name": "Wangwu"}))
记录总数
print(db.students.find().count())
删除一条记录
db.students.remove({"name": "Wangwu"})
创建索引
db.students.create_index([("name", pymongo.ASCENDING)])
更新数据库
db.students.update({"name": "Zhangsan"}, {"$set": {"age": 25}})
清空数据库
db.students.remove()
插入多条数据
zhangsan = {"name": "Zhangsan", "age": 20, "gender": "male"}
lisi = {"name": "Lisi", "age": 21, "gender": "male"}
wangwu = {"name": "Wangwu", "age": 22, "gender": "female"}
db.students.insert_many([zhangsan, lisi, wangwu])
对查询结果排序
for item in db.students.find().sort("name", pymongo.ASCENDING):
print(item)
入口函数
if name == 'main':
pass