2017-06-28 43 views
2

我有以下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 
    } ] 

回答

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

但是千萬注意,由於「屬性」是一個數組,那麼任何其他數組項也將是同樣如果該字段不存在,則返回null

備用是與$arrayElemAt再次從「屬性」輸入本身結合以提取索引:

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

哪隻返回「第一」或0索引元素作爲值:

{ "index_2": 10 }, 

所以在問題中爲什麼「屬性」是一個數組本身,是否可能有更多的條目,或者是否由於某種原因,您只在其中存儲了一個索引,並不清楚。但這些是你的選擇,至少可以訪問最後位置的「內部」元素。