[英]Return multiple documents which match the latest date with a single MongoDB query in Mongoose
The following is MongoDB query. 以下是MongoDB查询。 What is the best possible way to write this query in Mongoose?
用Mongoose编写此查询的最佳方法是什么?
db.logs.find({date: db.logs.find({}, {date:1,"_id":0}).sort({date:-1}).limit(1).toArray()[0].date})
There could be multiple documents with the same date and we need to retrieve all the documents that match the latest date. 可能有多个具有相同日期的文档,我们需要检索所有与最新日期匹配的文档。
The aggregation framework makes it possible to write this in a single query. 聚合框架使其可以在单个查询中编写。 You would require a pipeline that has an initial
$lookup
operator to do a self-join and within the $lookup
execute a pipeline on the joined collection which allows for uncorrelated sub-queries to return the latest date: 您将需要一个具有初始
$lookup
运算符的管道来进行自我联接,并在$lookup
执行对联接集合的管道,该管道允许不相关的子查询返回最新日期:
db.logs.aggregate([
{ "$lookup": {
"from": "logs",
"pipeline": [
{ "$sort": { "date": -1 } },
{ "$limit": 1 },
{ "$project": { "_id": 0, "date": 1 } }
],
"as": "latest"
} }
])
A further step is required to reshape the new field latest produced above so that the array is flattened. 还需要进一步的步骤来重塑上面最新生产的新磁场,以使阵列变平。 Use
$addFields
to reshape and $arrayElemAt
to flatten the array or use "$unwind"
: 使用
$addFields
重塑和$arrayElemAt
扁平化阵列,或使用"$unwind"
:
db.logs.aggregate([
{ "$lookup": {
"from": "logs",
"pipeline": [
{ "$sort": { "date": -1 } },
{ "$limit": 1 },
{ "$project": { "_id": 0, "date": 1 } }
],
"as": "latest"
} },
{ "$addFields": { "latest": { "$arrayElemAt": ["$latest", 0] } } }
])
The final step would be to filter the documents in the resulting pipeline using $expr
in a $match
stage since you will be comparing fields from the same document: 最后一步是在
$match
阶段使用$expr
过滤结果管道中的文档,因为您将比较同一文档中的字段:
db.logs.aggregate([
{ "$lookup": {
"from": "logs",
"pipeline": [
{ "$sort": { "date": -1 } },
{ "$limit": 1 },
{ "$project": { "_id": 0, "date": 1 } }
],
"as": "latest"
} },
{ "$addFields": { "latest": { "$arrayElemAt": ["$latest", 0] } } },
{ "$match": {
"$expr": {
"$eq": [ "$date", "$latest.date" ]
}
} }
])
Getting the query into Mongoose becomes a trivial exercise. 使查询进入Mongoose变得很简单。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.