Uploaded image for project: 'Core Server'
  1. Core Server
  2. SERVER-3415

Sorting by nested objects in an array

    XMLWordPrintableJSON

Details

    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.

      Attachments

        Activity

          People

            Unassigned Unassigned
            matwall Mat Wall
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

            Dates

              Created:
              Updated:
              Resolved: