如何在MongoDB的Users集合中一次查询获取首尾文档?
一次查询获取MongoDB Users集合的首尾文档(基于InsertedAt字段)
可以通过MongoDB的聚合管道实现一次查询返回首尾两条文档,以下是两种实用的实现方式:
方法一:使用$unionWith阶段(推荐,性能更优)
$unionWith能合并两个独立查询的结果,分别获取最早和最晚的文档后合并输出:
db.Users.aggregate([ // 获取InsertedAt最早的文档 { $unionWith: { coll: "Users", pipeline: [ { $sort: { InsertedAt: 1 } }, { $limit: 1 } ] } }, // 获取InsertedAt最晚的文档 { $unionWith: { coll: "Users", pipeline: [ { $sort: { InsertedAt: -1 } }, { $limit: 1 } ] } } ])
说明:
- 第一个
$unionWith管道通过升序排序InsertedAt,再用$limit:1取出最早插入的文档 - 第二个
$unionWith管道通过降序排序InsertedAt,再用$limit:1取出最晚插入的文档 - 两个管道的结果会自动合并为一个数组,正好返回你需要的两条文档
方法二:使用$group结合$first/$last(适合小集合)
如果集合数据量不大,可以先排序所有文档,再通过$group将文档存入数组,最后提取首尾元素:
db.Users.aggregate([ // 按InsertedAt升序排序全集合文档 { $sort: { InsertedAt: 1 } }, // 将所有文档存入一个数组 { $group: { _id: null, allDocs: { $push: "$$ROOT" } } }, // 提取数组的首尾元素并合并 { $project: { _id: 0, firstLast: { $concatArrays: [ [{ $arrayElemAt: ["$allDocs", 0] }], [{ $arrayElemAt: ["$allDocs", -1] }] ] } } }, // 将数组元素转为独立文档 { $unwind: "$firstLast" }, // 输出最终文档结构 { $replaceRoot: { newRoot: "$firstLast" } } ])
说明:
- 先对全集合排序,再将所有文档存入数组
- 用
$arrayElemAt分别取数组第0位(最早)和第-1位(最晚)的元素,再合并为新数组 - 最后通过
$unwind和$replaceRoot把数组元素转为独立文档输出 - 注意:此方法会加载全集合数据到内存,数据量大时性能较差,仅适合小集合场景
内容的提问来源于stack exchange,提问作者guirms
相关产品推荐
相关产品推荐

