我有这个系列:
{
"_id" : ObjectId("522f05f06f92046814003b84"),
"personal_id" : "0609150071",
"superstructure_id" : 1,
"name" : "David",
"surname" : "Bar",
"plays_often" : 1,
...
"created" : ISODate("2013-09-10T13:43:38Z")
}
{
"_id" : ObjectId("522f05f06f92046814003b84"),
"personal_id" : "0609150071",
"superstructure_id" : 1,
"name" : "David",
"surname" : "Bar",
"plays_often" : 1,
...
"created" : ISODate("2013-09-10T14:11:55Z")
}
...
需要查找记录:
条件:superstructure_id: 1
按personal_id
仅返回created
字段
然后按plays_often
限制为5
所以结果只有"personal_id" : "0609150071"
的记录,因为created
中有更新的日期时间:
{
"_id" : ObjectId("522f05f06f92046814003b84"),
"personal_id" : "0609150071",
"superstructure_id" : 1,
"name" : "David",
"surname" : "Bar",
"plays_often" : 1,
...
"created" : ISODate("2013-09-10T14:11:55Z")
}
这可能在mongodb吗?
答案 0 :(得分:1)
结果不包含整个原始文档。相反,它包含doc_id
字段,该字段是原始文档的_id
。最终的$project
运算符将重命名某些字段以匹配输入文档。例如,$group
运算符已将personal_id
重命名为_id
,因此$project
会将其更改回来。
db.goalie_tables.aggregate({
// Only select documents where superstructure_id = 1
$match: {
superstructure_id: 1
}
}, {
// Sort the documents for each personal_id in descending created date order
$sort: {
personal_id: 1,
created: -1
}
}, {
// Select the first document (ie, most recently created) for each personal_id
$group: {
_id: "$personal_id",
doc_id: {
$first: "$_id"
},
plays_often: {
$first: "$plays_often"
}
}
}, {
// Sort the results by plays_often (descending)
// Change to 1 for ascending
$sort: {
plays_often: -1
}
}, {
// Limit to 5 documents
$limit: 5
}, {
// Rename fields:
// _id => personal_id
// doc_id => _id
// plays_often => plays_often
$project: {
_id: "$doc_id",
personal_id: "$_id",
plays_often: "$plays_often"
}
});