McD*_*ott 5 arrays sorting children mongodb
我的数据如下所示:
{
"name":"dan",
"somestring":"asdf",
"friends":[
{
"name": "carl",
"height":180,
...
},
{
"name": "john",
"height":165,
...
},
{
"name": "jim",
"height":170,
...
}
]
},
...
Run Code Online (Sandbox Code Playgroud)
我想检索朋友按高度降序排序的文档。
我试过了,db.getCollection('users').find({"name" : "dan"}, {"friends" : 1}).sort({"friends.height" : -1})但朋友列表保持不变。
编辑:我搞砸了我的数据结构,我修复了数组看起来像一个数组......
一个选项是运行聚合:
friends.name管道应如下所示:
db.collection.aggregate([
{ $match: { name: 'dan' }},
{ $unwind: '$friends' },
{ $sort: { 'friends.height': -1 }},
{ $group: { _id: '$name', friends: { $push: '$friends'}}])
Run Code Online (Sandbox Code Playgroud)