Creating too many collections can decrease performance. With every collection, MongoDB creates a default _id index, which uses additional storage. 创建太多集合会降低性能。对于每个集合,MongoDB都会创建一个默认的_id索引,该索引使用额外的存储空间。If you create excessive collections, those collections and indexes can strain replica set resources and decrease performance.如果创建了过多的集合,这些集合和索引可能会使副本集资源紧张并降低性能。
About this Task关于此任务
Consider the following schema that stores daily temperature readings that are taken every hour. The 考虑以下存储每小时读取的每日温度读数的模式。温度数据库将每天的读数存储在单独的集合中。temperature database stores each day's readings in separate collections.
// Temperatures for May 10, 2024
{
_id: 1,
timestamp: "2024-05-10T010:00:00Z",
temperature: 60
},
{
_id: 2
timestamp: "2024-05-10T011:00:00Z",
temperature: 61
},
{
_id: 3
timestamp: "2024-05-10T012:00:00Z",
temperature: 64
}
...
// Temperatures for May 11, 2024
{
_id: 1,
timestamp: "2024-05-11T010:00:00Z",
temperature: 68
},
{
_id: 2
timestamp: "2024-05-11T011:00:00Z",
temperature: 72
},
{
_id: 3
timestamp: "2024-05-11T012:00:00Z",
temperature: 72
}
...
With an unbound number of collections, the number of default 如果集合数量不受限制,默认_id indexes can grow to degrade performance._id索引的数量可能会增加,从而降低性能。
Additionally, this approach requires a 此外,这种方法需要一个$lookup operation to query across multiple collections. $lookup operations add query complexity and can strain resources.$lookup操作来跨多个集合进行查询。$lookup操作增加了查询的复杂性,并可能使资源紧张。
To reduce the number of collections, drop or archive unused collections, or remodel your data schema by consolidating related collections, denormalizing data, or leveraging embedded documents where appropriate.为了减少集合的数量,请删除或存档未使用的集合,或通过整合相关集合、非规范化数据或在适当的情况下利用嵌入式文档来重塑数据模式。
Example示例
You can modify the schema to store each day's temperature readings in a single collection. For example:您可以修改模式,将每天的温度读数存储在一个集合中。例如:
db.dailyTemperatures.insertMany( [
{
_id: ISODate("2024-05-10T00:00:00Z"),
readings: [
{
timestamp: "2024-05-10T10:00:00Z",
temperature: 60
},
{
timestamp: "2024-05-10T11:00:00Z",
temperature: 61
},
{
timestamp: "2024-05-10T12:00:00Z",
temperature: 64
}
]
},
{
_id: ISODate("2024-05-11T00:00:00Z"),
readings: [
{
timestamp: "2024-05-11T10:00:00Z",
temperature: 68
},
{
timestamp: "2024-05-11T11:00:00Z",
temperature: 72
},
{
timestamp: "2024-05-11T12:00:00Z",
temperature: 72
}
]
}
] )
The updated schema requires fewer resources than the original. Instead of needing a separate index for each day, the default 更新的架构所需的资源比原始架构少。默认的_id index now facilitates queries by date._id索引现在方便了按日期查询,而不需要为每天单独设置索引。