按Mongo中嵌套数组中的文档值排序

Mar*_*jan 4 mongodb mongodb-query

我有一个名为Objects的集合.每个Object文档都有一个称为属性的嵌套文档数组.每个属性文档都有一个名称和一个值.

例如,假设我有这两个对象,每个对象都有两个属性(高度和宽度).我如何按高度对物体进行排序?

{
  "id": 1,
  "properties": [
    {
      "name": "height",
      "value": 170
    },
    {
      "name": "width",
      "value": 200
    },
  ]
},
{
  "id": 2,
  "properties": [
    {
      "name": "height",
      "value": 100
    },
    {
      "name": "width",
      "value": 300
    },
  ]
}
Run Code Online (Sandbox Code Playgroud)

Ana*_*lan 6

在大多数情况下,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}}
])
Run Code Online (Sandbox Code Playgroud)

编辑:保持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}}
])
Run Code Online (Sandbox Code Playgroud)