我有一个集合,其中包含以下对象:
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 将计算值保留为文档中的额外字段,后跟 $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}} ])