MongoDB将数据记录作为文档(BSON文档)存储在集合中。数据库包含一个或多个集合。
You can manage databases and collections using the Atlas UI, mongosh, or MongoDB Compass. This page covers Atlas UI procedures. For self-managed deployments, use mongosh or MongoDB Compass.
选择您的客户端:
MongoDB Compass is a powerful GUI for querying, aggregating, and analyzing your MongoDB data in a visual environment. To learn more, see MongoDB Compass.
Databases
创建数据库
MongoDB在您首次为其存储数据时创建数据库。切换到一个不存在的数据库并运行:
use myNewDB db.myNewCollection1.insertOne( { x: 1 } )
insertOne() 同时创建数据库myNewDB 和集合myNewCollection1(如果尚不存在)。确保这两个名称都遵循MongoDB命名限制。
集合
MongoDB 将文档存储在集合中。集合类似于关系数据库中的表。
创建集合
如果集合不存在,MongoDB 会在您首次存储该集合的数据时创建该集合。
db.myNewCollection2.insertOne( { x: 1 } ) db.myNewCollection3.createIndex( { y: 1 } )
如果集合不存在,insertOne() 和 createIndex() 都会创建各自的集合。确保集合名称遵循MongoDB命名限制。
显式创建
使用 db.createCollection() 可使用最大大小或验证规则等选项显式创建集合。如果没有这些选项, MongoDB会在您首次存储数据时自动创建集合。
要修改这些集合选项,请参阅collMod。
模式验证
默认下,集合中的文档不股票模式。字段和数据类型可能因文档而异。
您可以在插入和更新操作期间实施模式验证规则。
For MongoDB Atlas deployments, the Performance Advisor and the MongoDB Atlas UI detect common schema design issues and suggest modifications that follow MongoDB best practices. To learn more, see Schema Suggestions.
修改文档结构
要在集合的文档中添加、删除或重新键入字段,更新现有文档。
Unique Identifiers
系统为集合分配了一个不可变的 UUID,该 UUID 在所有副本集节点和分片中保持一致。