[SERVER-3415] Sorting by nested objects in an array Created: 12/Jul/11  Updated: 29/Aug/11  Resolved: 12/Jul/11

Status: Closed
Project: Core Server
Component/s: Index Maintenance, Querying
Affects Version/s: 1.8.2
Fix Version/s: None

Type: Question Priority: Major - P3
Reporter: Mat Wall Assignee: Unassigned
Resolution: Done Votes: 0
Labels: indexing, performance, query
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Participants:

 Description   

We have a document paraphrased as follows:

user {
emailAddress: "someEmail",
groups: [

{ groupName : "SomeName", groupJoinedDate: someDate}

,

{ groupName : "SomeOtherName", groupJoinedDate: someOtherDate}

...
]
...
}

The query that we need to run would be something like:

db.user.find(

{groups.groupName : "SomeName"}

).sort(

{groups.dateJoined : 1}

)

The issue would be that sorting by groups.dateJoined needs to refer to the specific group that we are trying to 'find'. It may be that the user has many tens of groups against their record and we would need to sort ONLY by the joined date of the group object we are specifically referring too, in the above example we want to sort user records by the date they joined "SomeName".

We think we get this to work by using compound indexes on the groupName + groupJoinedDate. One index for each direction, ie

db.user.ensureIndex(

{"group.name" : 1, "group.dateJoined" : 1}

)
db.user.ensureIndex(

{"group.groupName" : 1, "group.dateJoined" : -1}

)

Gives us sorted by ascending by default and we can force a descending query by adding .sort(

{"groups.dateJoined" : -1 }

to the query.

Does this sound like a legitimate way to accomplish this? Also is there a performance aspect to this query that I would need to be aware of?

Any thoughts or design suggestions welcome.



 Comments   
Comment by Mat Wall [ 12/Jul/11 ]

OK thanks.

I have a second index on the group.name which enforces uniqueness which should alleviate some of the issues you refer to with multiple matching.

So just to confirm,

(1) the solution above is OK
(2) I only need one index to allow sorting in either direction
(3) I can do db.collection.find(

{"group.name" : "SomeName}

).sort("group.dateJoined" : 1) AND db.collection.find(

{"group.name" : "SomeName}

).sort("group.dateJoined" : -1) for sorting purposes (although case 1 is unnecessary)

Many thanks

Comment by Scott Hernandez (Inactive) [ 12/Jul/11 ]

Yes, this should work for a single groupName match per document. If you get multiple matches per document (which is where all those index entries point) then it will not be so predictable what sort you will get.

You don't need two index; The index can be used forward or in reverse.

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