编写 MongoDB CRUD 操作
当涉及到在数据库系统中管理和操作数据时,我们必然会创建(Create
)、读取(Read
)、更新(Update
)和删除(Delete
)(CRUD
)文档。我们可以使用 MongoDB
的 CRUD
操作来实现这些功能。你可以在 https://www.google.com/search?q=https://docs.mongodb.com/manual/crud/ 上阅读更多关于 MongoDB CRUD
操作的信息。在本书中,我们将只看一个如何使用其中每个操作的简单示例:
-
创建(
Create
)操作:我们可以使用以下方法向集合创建或插入新的文档:
db.<collection>.insertOne(<document>) db.<collection>.insertMany([<document>, <document>, <document>,...])
请注意,如果你的数据库中不存在该集合,这些插入(
insert
)操作将自动为你创建它。 -
读取(
Read
)操作:我们可以使用以下方法从集合中获取文档:
db.<collection>.find(<query>, <projection>)
-
更新(
Update
)操作:我们可以使用以下方法修改集合中的现有文档:
db.<collection>.updateOne(<filter>, <update>, <options>) db.<collection>.updateMany(<filter>, <update>, <options>) db.<collection>.replaceOne(<filter>, <replacement>, <options>)
-
删除(
Delete
)操作:我们可以使用以下方法从集合中删除文档:
db.<collection>.deleteOne(<filter>, <options>) db.<collection>.deleteMany(<filter>, <options>)
有了这些简化的 CRUD
操作,你就可以在下一节中开始向数据库注入数据了,然后你就离创建一个功能齐全的 API
又近了一步。让我们开始吧!