对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。

查询固定大小集合

在查询固定大小集合时,如果不指定排序顺序,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 集合中 type 为 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。

以下查询返回 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 } ]