这是我的数据:
{
"112233": [
{
"pos_opts": {
"acc": 10,
"time": "123456"
}
},
{
"pos_opts": {
"acc": 20,
"time": "1234567"
}
},
{
"pos_opts": {
"acc": 20,
"time": "1234568"
}
},
{
"pos_opts": {
"acc": 30,
"time": "1234569"
}
}
],
"223344": [
{
"pos_opts": {
"acc": 10,
"time": "123456"
}
},
{
"pos_opts": {
"acc": 20,
"time": "1234567"
}
}
],
"_id": "75172"
}
我想得到结果:
SELECT 112233.children FROM x WHERE _id=75172 ORDER BY pos_opts.time DESC LIMIT 2
结果如:
[
{
"pos_opts": {
"acc": 30,
"time": "1234569"
}
},
{
"pos_opts": {
"acc": 20,
"time": "1234568"
}
}
]
这是我的代码(当然不起作用):
db.location.find({_id:"75172"}, {"112233": true}).sort({'pos_opts.time': -1})
感谢。
答案 0 :(得分:2)
您可以使用Aggregation Framework执行此操作。查询将如下所示:
db.location.aggregate(
{$match : {_id:"75172"}},
{$project : {"112233" : 1}},
{$unwind : "$112233"},
{$sort : {"112233.pos_opts.time" : -1}},
{$limit : 2}
)
结果如下:
{
"_id" : "75172",
"112233" : {
"pos_opts" : {
"acc" : 30,
"time" : "1234569"
}
}
},
{
"_id" : "75172",
"112233" : {
"pos_opts" : {
"acc" : 20,
"time" : "1234568"
}
}
}