如何访问嵌套数组中的最后一个位置

时间:2017-06-28 04:42:41

标签: mongodb mongodb-query aggregation-framework

我有以下json,想要访问" index_2'中包含的列表中的最后一个值。我需要添加什么 find({},{" attributes.index_2":1})仅返回index_2列表中的最后一个位置值。

'name': 'fred',
'attributes': [   {   
      'index_1': [   [   1, 2, 3, 4, 5 ]  ],
      'index_2': [   [   6, 7, 8, 9, 10] ],
      'line_number': 999
    }  ]

1 个答案:

答案 0 :(得分:0)

您实际上需要.aggregate()$arrayElemAt聚合运算符。

另请注意"attributes"本身就是一个“数组”,所以它取决于你只想要它的第一个元素或者它自己的条目的“全部”。

全部使用$map

db.collection.aggregate([
  { "$project": {
    "index_2": {
      "$map": {
        "input": "$attributes",
        "as": "attr",
        "in": {
          "$arrayElemAt": [ "$$attr.index_2", -1 ]
        }
      }
    }
  }}
])

会在您的样本上生成:

{ "index_2s": [ 10 ] }

但请注意,由于“attributes”是一个数组,因此在列表中也可以类似地提取任何其他数组项,或者如果该字段不存在则返回null

替代方法是再次与$arrayElemAt结合以从“属性”输入本身中提取索引:

db.collection.aggregate([
  { "$project": {
    "index_2": {
      "$arrayElemAt": [
        { "$map": {
          "input": "$attributes",
          "as": "attr",
          "in": {
            "$arrayElemAt": [ "$$attr.index_2", -1 ]
          }
        }},
        0
      ]
    }
  }}
])

只返回“first”或0索引元素作为值:

{ "index_2": 10  },

所以在问题中为什么“属性”本身就是一个数组本身并不清楚,因为是否有更多的条目或者由于某种原因你只在其中存储一个索引。但是你可以选择在最后一个位置至少访问“内部”元素。