Docs 菜单
Docs 主页
/
MongoDB Manual
/ / /

查询固定大小集合

在此页面上

  • 关于此任务
  • 多个并发写入
  • 开始之前
  • 创建固定大小集合
  • 插入示例数据
  • 步骤
  • 按插入顺序返回文档
  • 返回最近的文档
  • 了解详情

在查询固定大小集合时,如果不指定排序顺序,MongoDB 会按照插入的相同顺序返回结果,这意味着首先返回最早的文档。

使用自然排序高效地从集合中检索最近插入的元素。这类似于对日志文件使用 tail命令。

通常情况下,TTL(存活时间)索引比固定大小集合提供更好的性能和更大的灵活性。TTL 索引会过期,并根据日期类型字段的值和索引的 TTL 值从正常集合中删除数据。

固定大小集合会序列化写入操作,因此其并发插入、更新和删除性能比非固定大小集合差。在创建固定大小集合之前,请考虑是否可以改用 TTL 索引。

如果有并发写入者同时写入固定大小集合,MongoDB 不会保证按插入顺序返回文档。

1
db.createCollection("log", { capped: true, size: 100000 } )
2
db.log.insertMany( [
{
message: "system start",
type: "startup",
time: 1711403508
},
{
message: "user login attempt",
type: "info",
time: 1711403907
},
{
message: "user login fail",
type: "warning",
time: 1711404209
},
{
message: "user login success",
type: "info",
time: 1711404367
},
{
message: "user logout",
type: "info",
time: 1711404555
}
] )

以下示例展示了如何:

  • 按插入顺序返回文档

  • 返回最近的文档

查询 log 集合中 typeinfo 的文档,并使用默认排序顺序:

db.log.find( { type: "info" } )
[
{
_id: ObjectId("660204b74cabd75abebadbc2"),
message: 'user login attempt',
type: 'info',
time: 1711403907
},
{
_id: ObjectId("660204b74cabd75abebadbc4"),
message: 'user login success',
type: 'info',
time: 1711404367
},
{
_id: ObjectId("660204b74cabd75abebadbc5"),
message: 'user logout',
type: 'info',
time: 1711404555
}
]

文档将按照插入的顺序返回。

如要以相反的插入顺序(即最新的文档在前)返回文档,请指定 sort() 方法,并将 $natural 参数设置为 -1

以下查询返回 log 集合中的三个最新文档,从最新的文档开始:

db.log.find().sort( { $natural: -1 } ).limit(3)
[
{
_id: ObjectId("6601f2484cabd75abebadbbb"),
message: 'user logout',
type: 'info',
time: 1711404555
},
{
_id: ObjectId("6601f2484cabd75abebadbba"),
message: 'user login success',
type: 'info',
time: 1711404367
},
{
_id: ObjectId("6601f2484cabd75abebadbb9"),
message: 'user login fail',
type: 'warning',
time: 1711404209
}
]

后退

创建