4

在我的产品集合中,我可以找到在“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")
                }
        ]
}

如何使用 GB 发布日期按日期升序对结果进行排序?(例如顺序应该是baz, foo, bar)

请注意,我无法在客户端进行排序。

或者,我怎样才能更好地组织数据以使这成为可能。

编辑:我更改了“bar”的 FR 发布日期,以说明 vivek 的解决方案不正确。

4

1 回答 1

3

因为除了来自“GB”区域的元素之外你不需要release元素,你可以这样做aggregate

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}})

输出:

{
  "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
}
于 2013-02-28T13:44:53.453 回答