chemist
chemist

Reputation: 373

Sorting nested fields in MongoDB

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.

Upvotes: 2

Views: 733

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311865

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
}

Upvotes: 1

Related Questions