在MongoDB中,如何根据嵌入式对象中的属性对文档进行排序? [英] In MongoDB how can I sort documents based on a property in an embedded object?
问题描述
在我的产品集中,我可以找到在'GB'区域发布的所有产品:
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")
}
]
}
如何使用GB发布日期按升序对结果进行排序? (例如,订单应为baz,foo,bar)
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.
我将FR的发布日期更改为"bar",以说明vivek的解决方案不正确.
I changed the FR release date for 'bar' to illustrate that vivek's solution is not correct.
推荐答案
由于除了"GB"区域中的元素外,您还不需要release
元素,因此可以使用aggregate
来实现,如下所示:
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}})
输出:
{
"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
}
这篇关于在MongoDB中,如何根据嵌入式对象中的属性对文档进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!