Python——连接MongoDB

建立与MongoDB之间的连接:官方文档

#coding:utf-8

import pymongo

client = pymongo.MongoClient('127.0.0.1',27017)     # 建立与MongoDB的连接
#有用户名和密码时:pymongo.MongoClient('mongodb://用户名:密码@localhost:27017/基于哪个数据库进行验证的')

db = client.xingedb     # 切换使用的数据库

# 增
# db.t1.insert_one({'name':'abc','age':18})
# insert_more

# 改
# db.t1.update_one({'name':'abc'},{'$set':{'name':'123'}})
# update_more

# 删
# db.t1.delete_one({'name':'123'})
# delete_more

# 查
# cursor = db.t1.find({'age':{'$gt':17}})     # 返回一个游标对象
# find_one
#
# 显示方法1:
# for i in cursor:
#     print(i)
#
# 方法2:
# cursor.next()
# cursor.next()
# cursor.next()

# sort,skip,limit方法
#
# cursor = db.t1.find({'age':{'$gt':17}}).sort('_id',-1).limit(1).skip(1)
#
# for i in cursor:
#     print(i)

# count方法
# print(db.t1.count())

 

posted @ 2018-01-28 14:55  想54256  阅读(239)  评论(0编辑  收藏  举报