[SERVER-4451] Implement Positional Operator $ for Sorting Created: 07/Dec/11  Updated: 07/Apr/23

Status: Backlog
Project: Core Server
Component/s: Querying
Affects Version/s: None
Fix Version/s: None

Type: Improvement Priority: Major - P3
Reporter: Jarom Severson Assignee: Backlog - Query Execution
Resolution: Unresolved Votes: 10
Labels: query_triage
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Assigned Teams:
Query Execution
Participants:

 Description   

Given a collection with the following documents:

{ arr: [ {a: 1, b: 1}, {a: 2, b: 3} ] }
{ arr: [ {a: 1, b: 8}, {a: 2, b: 7} ] }
{ arr: [ {a: 1, b: 4}, {a: 2, b: 5} ] }

This new feature would allow the positional operator ($) to be used to sort by a field of the matched documents inside the array. For example, the following query would sort by the "b" field of the inner documents with "a" equal to 2:

db.test.find({"arr.a": 2}).sort({"arr.$.b": -1});

The documents matching documents would then be returned by the cursor in the following order:

{ arr: [ {a: 1, b: 8}, {a: 2, b: 7} ] }
{ arr: [ {a: 1, b: 4}, {a: 2, b: 5} ] }
{ arr: [ {a: 1, b: 1}, {a: 2, b: 3} ] }

------

Related posts:

https://groups.google.com/forum/#!topic/mongodb-user/w5ZVI4yraik

https://gist.github.com/e9182ceee4dc9de26f15



 Comments   
Comment by Ian Wright [ 07/Aug/18 ]

Workarounds are to use the aggregation framework unfortunately. Example https://stackoverflow.com/questions/51711544/mongo-incorrectly-sorting-on-array-field?noredirect=1#comment90396956_51711544

Comment by Chris [ 05/Aug/12 ]

Is there a workaround for this?

Generated at Thu Feb 08 03:06:01 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.