对数组 mongodb 的索引进行排序 [英] Sorting on index of array mongodb
问题描述
我有一个集合,其中包含以下对象:
I have a collection where i have objects like:
{
"_id" : ObjectId("5ab212249a639865c58b744e"),
"levels" : [
{
"levelId" : 0,
"siteId" : "5a0ff11dc7bd083ea6a706b1",
"title" : "Hospital Services"
},
{
"levelId" : 1,
"siteId" : "5a0ff220c7bd083ea6a706d0",
"title" : "Reference Testing"
},
{
"levelId" : 2,
"siteId" : "5a0ff24fc7bd083ea6a706da",
"title" : "Des Moines(Reference Testing)"
}
]
}
我想对级别数组的第二个对象的标题字段进行排序,例如levels.2.title
目前我的 mongo 查询看起来像:
I want to sort on the title field of 2nd object of levels array e.g. levels.2.title
Currently my mongo query looks like:
db.getCollection('5aaf63a69a639865c58b2ab9').aggregate([
{$sort : {'levels.2.title':1}}
])
但它没有给出预期的结果.
请帮忙.
But it is not giving desired results.
Please help.
推荐答案
您可以在 3.6 中尝试以下查询.
You can try below query in 3.6.
db.col.aggregate({$sort:{"levels.2.title":1}});
这种聚合和查找语义在 3.4 中是不同的.更多关于 jira
这里
This aggregation and find semantics are different in 3.4. More on jira
here
所以
db.col.find().sort({"levels.2.title":1})
按预期工作,但聚合排序未按预期工作.
works as expected and aggregation sort is not working as expected.
在 3.4 中使用以下聚合.
Use below aggregation in 3.4.
使用$arrayElemAt
在 $addFields
中投影第二个元素a> 将计算值保留为文档中的额外字段,后跟 $sort
按字段排序.
Use $arrayElemAt
to project the second element in $addFields
to keep the computed value as the extra field in the document followed by $sort
sort on field.
$project
排除排序字段以获得预期输出.
$project
with exclusion to drop the sort field to get expected output.
db.col.aggregate([
{"$addFields":{ "sort_element":{"$arrayElemAt":["$levels", 2]}}},
{"$sort":{"sort_element.title":-1}},
{"$project":{"sort_element":0}}
])
另外,您可以使用 $let
表达式直接输出$addFields
阶段.
Also, You can use $let
expression to output the title field directly in $addFields
stage.
db.col.aggregate([
{"$addFields":{ "sort_field":{"$let:{"vars":{"ele":{$arrayElemAt":["$levels", 2]}}, in:"$$ele.title"}}}},
{"$sort":{"sort_field":-1}},
{"$project":{"sort_field":0}}
])
这篇关于对数组 mongodb 的索引进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!