以下是documents
:
[
{
"reports" : [
{
"date" : ISODate("2015-05-18T18:30:00.000Z"),
"creator" : ObjectId("55ce1372f260b80927aade84"),
"title" : "Vestibulum pulvinar leo ut risus eleifend elit"
}, {
"date" : ISODate("2015-05-15T18:30:00.000Z"),
"creator" : ObjectId("55ce136af260b80927aade83"),
"title" : "Nunc sit amet nisl ut dolor lobortis varius ut vestibulum felis"
}
]
}, {
"reports" : [
{
"date" : ISODate("2015-06-23T01:00:00.000Z"),
"creator" : ObjectId("55ce136af260b80927aade83"),
"title" : "Nam eget diam eu nibh placerat"
}, {
"date" : ISODate("2015-06-07T01:00:00.000Z"),
"creator" : ObjectId("55ce1372f260b80927aade84"),
"title" : "Proin auctor non justo eget porta"
}, {
"date" : ISODate("2015-06-10T01:00:00.000Z"),
"creator" : ObjectId("55ce1372f260b80927aade84"),
"title" : "Curabitur pellentesque neque felis"
}
]
}
]
对于每个查询,我都无法确定document.reports
中报告的顺序,因此,我想先在reports.date
document
中按documents
对其进行排序,然后找到{{1} } {reports.0.creator : ObjectId("55ce1372f260b80927aade84")
或者换句话说,
在documents
之前查找reports.creator
,其中reports.date
是最低/最高。
答案 0 :(得分:0)
如果您想要Find documents by reports.creator where reports.date is the minimum
,首先$unwind
reports
然后匹配creator
,可以使用简单的方法,按升序排序,并通过应用限制1选择文档
要获得最大反向排序参数以降序。
这是一个查询:
db.collection.aggregate({
$unwind: "$reports"
}, {
$match: {
"reports.creator": ObjectId("55ce1372f260b80927aade84")
}
}, {
$sort: {
"reports.date": 1
}
}, {
$limit: 1
})
等效的node.js代码如下:
collection.aggregate([{
$unwind: "$reports"
}, {
$match: {
"reports.creator": ObjectId("55ce1372f260b80927aade84")
}
}, {
$sort: {
"reports.date": 1
}
}, {
$limit: 1
}], function(err, result) {
console.log(result);
db.close();
});