查询受限集合
当您查询未指定排序顺序的受限集合时,MongoDB会按它们被插入的相同顺序返回结果,这意味着最早插入的文档先返回。
使用自然排序来有效地从集合中检索最新插入的元素。这类似于在日志文件上使用tail
命令。
关于此任务
通常,与受限集合相比,TTL(生存时间)索引提供更好的性能和更大的灵活性。TTL索引根据日期类型的字段值和索引的TTL值过期并从普通集合中删除数据。
受限集合序列化写入操作,因此并发插入、更新和删除的性能比非受限集合差。在创建受限集合之前,请考虑是否可以使用TTL索引。
并发写入
如果受限集合有并发写入者,MongoDB不能保证文档按插入顺序返回。
开始之前
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 } ]