我有一个称为对象的集合。每个对象文档都有一个嵌套的文档数组,称为属性。每个属性文档都有一个名称和一个值。
例如,假设我有这两个对象,每个对象都有两个属性(高度和宽度)。如何按高度对物体进行排序?
{
"id": 1,
"properties": [
{
"name": "height",
"value": 170
},
{
"name": "width",
"value": 200
},
]
},
{
"id": 2,
"properties": [
{
"name": "height",
"value": 100
},
{
"name": "width",
"value": 300
},
]
}
在大多数情况下,aggregation framework
每当您处理数组时,MongoDB就是您的朋友。看一下$unwind
可用于将数组拆分为单个文档的运算符。我在下面发布了一个示例查询,以对文档进行排序height
。请注意,可以$project
在聚合管道中使用运算符来更好地格式化结果。
db.objects.aggregate([
// De-normalize the 'properties' array
{$unwind:"$properties"},
// Filter for only height
{$match:{"properties.name":"height"}},
// Sort by 'height' in ascending order. Use -1 for descending
{$sort:{"properties.value":1}}
])
编辑:保持properties
元素完整的一种方法是使它的副本仅用于排序。下面是一个示例:
db.objects.aggregate([
// Make a copy of the 'properties' element
{$project:{properties:1, sortfield:"$properties"}},
{$unwind:"$sortfield"},
{$match:{"sortfield.name":"height"}},
{$sort:{"sortfield.value":1}},
// Get rid of 'sortfield'
{$project:{properties:1}}
])
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句