问题
I have a schema like this:
{
"_id" : "555",
"connections" : [
{
"id" : 111
"time" : 1456439249
},
{
"id" : 222
"time" : 1556412345
}
...
}
"users" : [
"111" : {
"id" : 111
"name" : "Michael"
},
"222" : {
"id" : 222
"name" : "Jim"
}
...
}
I want to get sorted connections by time and users data.
I'm trying with this:
db.getCollection('mycollecion')
.find(
{'_id' : '555'},
{'_id' : 0, 'connections' : 1, 'users' : 1}
).sort({'connections.time' : 1})
Probably "connections.time" is not the correct path, because it's array.
How I can sort connections by the subfield "time"?
And it would be possible in the same query filter "users" by appearing on connections ids?
回答1:
Please try to do it through .aggregation()
> db.mycollecion.aggregate([
{$unwind: '$connections'},
{$sort: {'connections.time': 1}},
{$group: {
_id: '$_id',
connections: {$push: '$connections'}
}
}]);
来源:https://stackoverflow.com/questions/35635755/sort-subfields-with-unknown-parent