Reputation: 6814
This is my data:
{
"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"
}
I want to get the result:
SELECT 112233.children FROM x WHERE _id=75172 ORDER BY pos_opts.time DESC LIMIT 2
the result like:
[
{
"pos_opts": {
"acc": 30,
"time": "1234569"
}
},
{
"pos_opts": {
"acc": 20,
"time": "1234568"
}
}
]
This is my code (of course doesn't works):
db.location.find({_id:"75172"}, {"112233": true}).sort({'pos_opts.time': -1})
Thanks.
Upvotes: 1
Views: 472
Reputation: 26012
You can do it with Aggregation Framework. Query will look like :
db.location.aggregate(
{$match : {_id:"75172"}},
{$project : {"112233" : 1}},
{$unwind : "$112233"},
{$sort : {"112233.pos_opts.time" : -1}},
{$limit : 2}
)
Result will look like :
{
"_id" : "75172",
"112233" : {
"pos_opts" : {
"acc" : 30,
"time" : "1234569"
}
}
},
{
"_id" : "75172",
"112233" : {
"pos_opts" : {
"acc" : 20,
"time" : "1234568"
}
}
}
Upvotes: 2