nick
nick

Reputation: 1379

In MongoDB how can I sort documents based on a property in an embedded object?

In my products collection, I can find all products that have been released in the region 'GB':

> db.products.find({'release.region':'GB'}).pretty();

{
        "_id" : "foo",
        "release" : [
                {
                        "region" : "GB",
                        "date" : ISODate("2012-03-01T00:00:00Z")
                },
                {
                        "region" : "US",
                        "date" : ISODate("2012-09-01T00:00:00Z")
                }
        ]
}
{
        "_id" : "bar",
        "release" : [
                {
                        "region" : "FR",
                        "date" : ISODate("2010-07-01T00:00:00Z")
                },
                {
                        "region" : "GB",
                        "date" : ISODate("2012-05-01T00:00:00Z")
                }
        ]
}
{
        "_id" : "baz",
        "release" : [
                {
                        "region" : "GB",
                        "date" : ISODate("2011-05-01T00:00:00Z")
                },
                {
                        "region" : "NZ",
                        "date" : ISODate("2012-02-01T00:00:00Z")
                }
        ]
}

How can I sort the results in ascending date order, using the GB release date? (e.g. the order should be baz, foo, bar)

Note, I cannot do the sorting on the client side.

Alternatively, how can I better organise the data to make this possible.

Edit: I changed the FR release date for 'bar' to illustrate that vivek's solution is not correct.

Upvotes: 4

Views: 2104

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 312129

Because you don't need the release elements besides the ones from the "GB" region, you can do it with aggregate like this:

db.products.aggregate(
    // Filter the docs to just those containing the 'GB' region
    { $match: {'release.region': 'GB'}},
    // Duplicate the docs, one per release element
    { $unwind: '$release'},
    // Filter the resulting docs to just include the ones from the 'GB' region
    { $match: {'release.region': 'GB'}},
    // Sort by release date
    { $sort: {'release.date': 1}})

output:

{
  "result": [
    {
      "_id": "baz",
      "release": {
        "region": "GB",
        "date": ISODate("20110501T00:00:00Z")
      }
    },
    {
      "_id": "foo",
      "release": {
        "region": "GB",
        "date": ISODate("20120301T00:00:00Z")
      }
    },
    {
      "_id": "bar",
      "release": {
        "region": "GB",
        "date": ISODate("20120501T00:00:00Z")
      }
    }
  ],
  "ok": 1
}

Upvotes: 3

Related Questions