mongoDB非关系型数据库学习记录
MongoDB是一个基于分布式文件存储的开源数据库系统,其主要特点是高性能、易部署、易使用,存储数据非常灵活。非关系型数据库不使用SQL作为查询语言。
以下是一些MongoDB的基本操作和示例代码:
- 连接MongoDB数据库
在Python中,我们可以使用pymongo
库来连接MongoDB。首先需要安装这个库,可以使用pip安装:
pip install pymongo
然后,我们可以使用以下代码连接到MongoDB:
from pymongo import MongoClient
client = MongoClient('localhost', 27017)
db = client['test_database']
collection = db['test_collection']
- 插入文档
在MongoDB中,我们可以使用insert_one()
或insert_many()
方法来插入文档。
post = {"name": "test", "age": 20}
collection.insert_one(post)
posts = [
{"name": "test1", "age": 21},
{"name": "test2", "age": 22}
]
collection.insert_many(posts)
- 查询文档
在MongoDB中,我们可以使用find_one()
或find()
方法来查询文档。
# 查询单个文档
document = collection.find_one({"name": "test"})
print(document)
# 查询多个文档
for doc in collection.find({"name": "test"}):
print(doc)
- 更新文档
在MongoDB中,我们可以使用update_one()
或update_many()
方法来更新文档。
collection.update_one({"name": "test"}, {"$set": {"name": "test_new"}})
collection.update_many({"name": "test"}, {"$set": {"name": "test_new"}})
- 删除文档
在MongoDB中,我们可以使用delete_one()
或delete_many()
方法来删除文档。
collection.delete_one({"name": "test"})
collection.delete_many({"name": "test"})
- 创建索引
在MongoDB中,我们可以使用create_index()
方法来创建索引,以提高查询效率。
collection.create_index([("name", pymongo.ASCENDING)])
以上就是一些基本的MongoDB操作和示例代码,更多详细的操作和特性可以参考MongoDB官方文档。
评论已关闭