Sorting based on subdocument

75 views
Skip to first unread message

Rajagopal Ravikumar

unread,
Jul 7, 2014, 7:57:55 PM7/7/14
to mongod...@googlegroups.com
Hi Guys,

I am trying to get some help in querying mongo to return a sorted set based on value in the subdocument. Specifically for the below document structure I am looking to get sorted results based on systemtags: [ {key:"displayOrder", value:<long number>]. The sorting should be based on long number value for the displayOrder key. sort order does not matter though. It can be ascending or descending. Appreciate you guys' help on this.

This is how my document looks like -

{    "_id" : NumberLong("2147483692030"),
    "assetType" : "DOCUMENT",
    "createDate" : ISODate("2014-07-07T10:02:38.335Z"),
    "dataCenter" : "AU1",
    "dateTaken" : NumberLong("107136966500011"),
    "files" : [
        {
            "fileType" : "HI1",
            "url" : "string1",
            "width" : NumberLong(1600),
            "height" : NumberLong(1200),
            "size" : NumberLong(0)
        },
        {
            "fileType" : "HI2",
            "url" : "string2",
            "width" : NumberLong(0),
            "height" : NumberLong(0),
            "size" : NumberLong(0)
        },
        {
            "fileType" : "HI3",
            "url" : "String3",
            "width" : NumberLong(800),
            "height" : NumberLong(600),
            "size" : NumberLong(0)
        }
    ],
    "hashAccountId" : NumberLong("9916768824"),
    "markedForDelete" : false,
    "ownerAccountId" : NumberLong("1003816101211"),
    "parentCollectionReferences" : [
        {
            "ownerAccountId" : NumberLong("1003816101211"),
            "collectionId" : NumberLong("214748366302011")
        }
    ],
    "systemTags" : [
        {
            "value" : "JQK",
            "key" : "uploadTypeCode"
        },
        {
            "value" : NumberLong("1404727360843"),
            "key" : "displayOrder"
        },
        {
            "value" : "/ar=1/pe",
            "key" : "journalDeveloper"
        }
     ]
}




William Berkeley

unread,
Jul 8, 2014, 2:12:42 PM7/8/14
to mongod...@googlegroups.com
Hi Rajagopal. Without changing your schema, the method available to sort on the value of the displayOrder key is to identify the value for that key using the position in the array:

db.test.find({*your query*}).sort({"systemTags.1.value" : 1})

You cannot identify the value using its key, so you need the displayOrder key to be in a fixed position in the array.

-Will
Reply all
Reply to author
Forward
0 new messages