MongoDB-api-pymongo(1)

MongoDB api 之 pymongo

安装pymongo

1
$ pip install pymongo

Python使用pymongo连接数据库

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
improt pymongo  # 导入pymongo包

# 连接mongodb

connection = pymongo.MongoClient("mongodb://localhost")

# 使用数据库
db = connection.DATABASE_NAME

# 使用集合
COLLECTION_NAME = db.COLLECTION_NAME_IN_DATABASE_NAME

# 使用find函数返回cursor
def find():
query = {'' : ''}
# 返回cursor
try:
cursor = COLLECTION_NAME.find(query)
except Exception as e:
print("Unexpected error, ", type(e), e)
# iterate
for doc in cursor:
print(doc)

# 使用find_one返回一个文档

def find_one():
query = {'' : ''}
try:
doc = COLLECTION_NAME.find_one(query)
except Exception as e:
print("Unexpected error,", type(e), e)