2

I have the following data structure:

{  
  'url' : 'www.example.com',
  'title' : 'This is a title',
  'data' : [ 
             [{'name': 'abcdefg'}, {'nmr': 'hijklmnop'}],
             [{'name': 'hijklmnop'}, {'nmr': 'abcdefg'}]
          ]
},

{  
  'url' : 'www.example_2.com',
  'title' : 'This is a title_2',
  'data' : [ 
             [{'name': 'abcdefg'}, {'nmr': 'hijklmnop'}],
             [{'name': 'hijklmnop'}, {'nmr': 'abcdefg'}],
             [{'name': 'abcdefg'}, {'nmr': 'hijklmnop'}]
           ]
}

I need to sort by 'url' (descending order) according to the total number of names in 'data'. I expect to see something like this:

www.example_2.com : 3

www.example.com : 2

Any help is highly appreciated.

JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
chemist
  • 373
  • 9
  • 20

1 Answers1

1

You can use the $size operator in aggregate to access the size of an array field and then $sort on it.

In the shell:

db.test.aggregate([
    {$project: {url: 1, count: {$size: '$data'}}},
    {$sort: {count: -1}}
])

Output

{
    "result" : [ 
        {
            "_id" : ObjectId("53dadaf8393fa0461f92333c"),
            "url" : "www.example_2.com",
            "count" : 3
        }, 
        {
            "_id" : ObjectId("53dadaf8393fa0461f92333b"),
            "url" : "www.example.com",
            "count" : 2
        }
    ],
    "ok" : 1
}
JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
  • Thanks for you help, but for some reason I get this error: "errmsg" : "exception: invalid operator '$size'". Did i do something wrong? – chemist Aug 01 '14 at 01:08
  • @chemist The `$size` operator was added in the 2.6 release, so it may be that you're running an older version. – JohnnyHK Aug 01 '14 at 01:09
  • @ JohnnyHK You were right. I just upgraded MongoDB and everything works great. Thanks! – chemist Aug 01 '14 at 01:46