2020年面向初学者的终极python mongodb指南

Python can be used in database applications. One of the most popular NoSQL databases is MongoDB. MongoDB stores data in JSON-like documents, which makes the database very flexible and scalable. In this article, I hope to teach you the fundamentals of MongoDB in Python.

Python可用于数据库应用程序。 最受欢迎的NoSQL数据库之一是MongoDB。 MongoDB将数据存储在类似JSON的文档中,这使数据库非常灵活且可扩展。 在本文中,我希望教您使用Python编写MongoDB的基础知识。

If you are new to Python, check out my Python Guide as well:

如果您不熟悉Python,请同时参阅我的Python指南

入门 (Getting Started)

Python needs a MongoDB driver to access the MongoDB database. We recommend that you use PIP to install “PyMongo”. PIP is most likely already installed in your Python environment.

Python需要MongoDB驱动程序才能访问MongoDB数据库。 我们建议您使用PIP安装“ PyMongo”。 PIP很可能已经安装在您的Python环境中。

C:\Users\Your Name\AppData\Local\Programs\Python\Python36-32\Scripts>python -m pip install pymongo

To test if your PyMongo has been installed successfully run the following line of code:

要测试您的PyMongo是否已成功安装,请运行以下代码行:

import pymongo

If the above code was executed with no errors, “pymongo” is installed and ready.

如果以上代码正确执行,则“ pymongo”已安装并准备就绪。

创建数据库 (Creating a Database)

To create a database in MongoDB, start by creating a MongoClient object, then specify a connection URL with the correct IP address and the name of the database you want to create.

要在MongoDB中创建数据库,请先创建一个MongoClient对象,然后指定具有正确IP地址和要创建的数据库名称的连接URL。

import pymongomyclient = pymongo.MongoClient("mongodb://localhost:27017/")mydb = myclient["mydatabase"]

检查数据库是否存在 (Check if a Database Exists)

dblist = myclient.list_database_names()
if "mydatabase" in dblist:
print("The database exists.")

创建收藏 (Creating a Collection)

To create a collection in MongoDB, use the database object, and specify the name of the collection you want to create.

要在MongoDB中创建集合,请使用数据库对象,然后指定要创建的集合的名称。

import pymongomyclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]mycol = mydb["users"]

检查集合是否存在 (Check if a Collection Exists)

You can check if a collection exists in a database by listing all collections:

您可以通过列出所有集合来检查数据库中是否存在一个集合:

collist = mydb.list_collection_names()
if "customers" in collist:
print("The collection exists.")

(Insert)

To insert a record or document as it is called in MongoDB, into a collection, we use the ‘insert_one()’ method.

要将在MongoDB中调用的记录或文档插入集合,我们使用'insert_one()'方法。

import pymongomyclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["users"]mydict = { "username": "bryan.dijkhuizen", "password": "********" }x = mycol.insert_one(mydict)

The ‘insert_one’ method returns a value, the result of the insert. So if you want to retrieve the ID of your just added user:

“ insert_one”方法返回一个值,即插入的结果。 因此,如果要检索刚添加的用户的ID:

import pymongomyclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["users"]mydict = { "username": "bryan.dijkhuizen", "password": "********" }x = mycol.insert_one(mydict)print(x.inserted_id)

插入许多文件 (Insert Many Documents)

To insert multiple documents into a collection in MongoDB, we use the ‘insert_many()’ method.

要将多个文档插入MongoDB的集合中,我们使用'insert_many()'方法。

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["users"]mylist= [
{ "username": "bryan.dijkhuizen", "password": "********" },
{ "username": "bryan.dijkhuizen2", "password": "********" },]x = mycol.insert_many(mylist)#print list of the _id values of the inserted documents:
print(x.inserted_ids)

(Find)

To select data from a collection in MongoDB, we can use the ‘find_one()’ method.

要从MongoDB中的集合中选择数据,我们可以使用'find_one()'方法。

import pymongomyclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["users"]x = mycol.find_one()print(x)

To select data from a table in MongoDB, we can also use the ‘find()’ method.

要从MongoDB中的表中选择数据,我们还可以使用'find()'方法。

import pymongomyclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["users"]for x in mycol.find():
print(x)

This will return all the documents from the database.

这将从数据库返回所有文档。

If you want to return specific fields, you can use the ‘find()’ method with parameters:

如果要返回特定字段,则可以将'​​find()'方法与参数一起使用:

import pymongomyclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["users"]for x in mycol.find({},{ "username": "bryan.dijkhuizen2",}):
print(x)

分类 (Sort)

The ‘sort()’ method is used for what it looks like. It will be used for: sorting the results. Sort the result alphabetically by name:

'sort()'方法用于外观。 它将用于:对结果进行排序。 按名称的字母顺序对结果进行排序:

import pymongomyclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["users"]mydoc = mycol.find().sort("name")for x in mydoc:
print(x)

Sort the results reverse alphabetically by name:

按名称的字母顺序对结果进行排序:

import pymongomyclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["users"]mydoc = mycol.find().sort("username", -1)for x in mydoc:
print(x)

删除 (Delete)

If you want to delete a document from your database, you can use the ‘delete_one()’ method to delete just one:

如果要从数据库中删除文档,可以使用'delete_one()'方法仅删除一个:

import pymongomyclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["users"]myquery = { "username": "bryan.dijkhuizen2" }mycol.delete_one(myquery)

Delete many documents

删除许多文件

To delete more than one document, use the ‘delete_many()’ method:

要删除多个文档,请使用'delete_many()'方法:

import pymongomyclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["users"]myquery = { "username": {"$regex": "^b"} }x = mycol.delete_many(myquery)print(x.deleted_count, " documents deleted.")

Delete All Documents

删除所有文件

Delete all documents in the “users” collection:

删除“用户”集合中的所有文档:

import pymongomyclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["users"]x = mycol.delete_many({})print(x.deleted_count, " documents deleted.")

删除收藏 (Delete Collection)

You can delete a table or collection as it is called in MongoDB using the ‘drop()’ method.

您可以使用“ drop()”方法删除在MongoDB中调用的表或集合。

import pymongomyclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["users"]mycol.drop()

更新资料 (Update)

You can update a record or document as it is called in MongoDB, by using the ‘update_one()’ method.

您可以使用'update_one()'方法更新在MongoDB中调用的记录或文档。

import pymongomyclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["users"]myquery = { "username": "bryan.dijkhuizen" }
newvalues = { "$set": { "password": "**************" } }mycol.update_one(myquery, newvalues)#print "users" after the update:
for x in mycol.find():
print(x)

You can do the same thing with ‘update_many()’ Then you should change your query.

您可以使用“ update_many()”执行相同的操作,然后更改查询。

结论 (Conclusion)

To conclude this guide, I’d like to say thank you for reading, and I hope that you have now learned the fundaments of Python MongoDB, and you will be able to work with it yourself!

总结本指南,我想感谢您的阅读,希望您现在已经了解了Python MongoDB的基础知识,并且可以自己使用它!

翻译自: https://levelup.gitconnected.com/the-ultimate-python-mongodb-guide-for-beginners-in-2020-c8fa06a198f8

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值