文档菜单
文档首页
/
MongoDB 手册
/ / /

查询受限集合

在本页

  • 关于此任务
  • 并发写入
  • 开始之前
  • 创建受限集合
  • 插入示例数据
  • 步骤
  • 按插入顺序返回文档
  • 返回最新文档
  • 了解更多

当您查询未指定排序顺序的受限集合时,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
}
] )

以下示例展示了如何

  • 按插入顺序返回文档

  • 返回最新文档

查询日志集合中类型为info的文档,并使用默认排序顺序

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一起使用。

以下查询从日志集合中返回三个最新文档,以最新文档开始

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
}
]

返回

创建