pymongo

来源:互联网 发布:js两个字符串比较 编辑:程序博客网 时间:2024/05/21 07:51

环境描述

  • Python 3.6.3
  • pip 9.0.1
  • Windows 10

安装

pip install pymongo

与数据库建立连接

from pymongo import MongoClient # 导入包user = "root" # 连接的用户名password = "123456" # 密码host = "localhost" # 连接的数据库主机uri = "mongodb://{user}:{password}@{host}".format(user=user,password=password,host=host) # 设置连接的uriclient = MongoClient(uri) # 建立连接

获取数据库

db = client.db_name # 访问属性的方式db = client["db_name"] # 采用字典的方式

获取集合

collection = db.collection_name # 范文属性的方式collection = db["collection_name"] # 字典方式获取

插入文档

插入一个文档

client = MongoClient(uri)db = client.newspapertest = db.testdocument = { # 要插入的文档    "name":789}# insert_one()一次插入一个文档doc_id = test.insert_one(document).inserted_id # 返回文档_idprint(doc_id)

批量插入

client = MongoClient(uri)db = client.newspapertest = db.testdocuments = [{"name":789},{"name":456}]# 要插入的文档# insert_many() 批量插入文档数组result = test.insert_many(documents)print(result.inserted_ids)

查询文档

单文档查询

result1 = test.find_one() # 查找集合中的第一个文档result2 = test.find_one({"name":456}) # 查找符合条件的文档的第一个print(result1)print(result2)

多文档查询
find()返回一个Cursor实例,它允许遍历所有匹配的文档

results = test.find() # 查找集合中所有的文档print(results.count()) # 返回查询结果的条数for res in results: #遍历    print(res)results = test.find({"name":789}) # 查找所有匹配的文档print(results.count()) # 返回查询结果的条数for res in results: # 遍历    print(res)

find()中的查询条件可以是MongoDB中的其他条件,包括范围查询和and,or操作

建立唯一索引

添加索引可以帮助加速某些查询,并且还可以添加额外的功能来查询和存储文档。在这个例子中,将演示如何在一个键上创建一个唯一的索引,该索引将拒绝已经存在值的文档插入。

result = db.test.create_index([('name', pymongo.ASCENDING)], unique=True)sorted(list(db.test.index_information()))

现在有两个索引:一个是MongoDB自动创建的在_id索引,另一个是刚刚创建在name上的索引。

原创粉丝点击