2017-09-28 2 views
0

하위 컬렉션이 있으며이 컬렉션의 첫 번째 항목의 특정 하위 필드를 투영하려고합니다. 다음과 같은 있지만 배열의 모든 요소에 대한 필드를 프로젝트에만 있습니다.Mongo aggregation, 배열의 첫 번째 요소의 하위 필드를 투영합니다.

Items는 Orders의 하위 집합이며 각 Item 개체에는 Details 하위 개체와 그 아래에 ItemName이 있습니다. 목록에서 FIRST 항목의 항목 이름 만 반환하고 싶습니다. 그러면 목록의 모든 항목에 대한 항목 이름이 반환됩니다.

어떻게 조정할 수 있습니까?

db.getCollection('Orders').aggregate 
([ 
{ $match : { "Instructions.1" : { $exists : true }}}, 
{ $project: { 
    _id:0, 
    'UserId': '$User.EntityId', 
    'ItemName': '$Items.Details.ItemName' 
    } 
} 
]); 

업데이트 : 당신은 적어도 MongoDB를의 V3.2을 사용하는 경우

{ 
    "_id" : "order-666156", 
    "State" : "ValidationFailed", 
    "LastUpdated" : { 
     "DateTime" : ISODate("2017-09-26T08:54:16.241Z"), 
     "Ticks" : NumberLong(636420128562417375) 
    }, 
    "SourceOrderId" : "666156", 
    "User" : { 
     "EntityId" : NumberLong(34450), 
     "Name" : "Bill Baker", 
     "Country" : "United States", 
     "Region" : "North America", 
     "CountryISOCode" : "US", 
    }, 
    "Region" : null, 
    "Currency" : null, 
    "Items" : [ 
     { 
      "ClientOrderId" : "18740113", 
      "OrigClientOrderId" : "18740113", 
      "Quantity" : NumberDecimal("7487.0"), 
      "TransactDateTime" : { 
       "DateTime" : Date(-62135596800000), 
       "Ticks" : NumberLong(0) 
      }, 
      "Text" : null, 
      "LocateRequired" : false, 
      "Details" : { 
       "ItemName" : "Test Item 1", 
       "ItemCost" : 1495.20 
      } 
     }, 
     { 
      "ClientOrderId" : "18740116", 
      "OrigClientOrderId" : "18740116", 
      "Quantity" : NumberDecimal("241.0"), 
      "TransactDateTime" : { 
       "DateTime" : Date(-62135596800000), 
       "Ticks" : NumberLong(0) 
      }, 
      "Text" : null, 
      "LocateRequired" : false, 
      "Details" : { 
       "ItemName" : "Test Item 2", 
       "ItemCost" : 2152.64 
      } 
     } 
    ] 

} 
+0

시도'{ '항목 이름': {$의 arrayElemAt : [ '$ Items.Details.ItemName', 0]}}'[당신이 MongoDB를 프로젝션 집계에서 특정 배열 항목에 액세스하려면 어떻게의 – Veeram

+0

가능한 중복? ] (https://stackoverflow.com/questions/30997736/how-do-you-access-a-specific-array-item-in-mongodb-projection-aggregation) – Veeram

답변

1

당신이에 대한 $arrayElemAt 연산자를 사용할 수 있습니다. 아래 쿼리는 원하는 것을 처리합니다. 그러나 "Instructions.1": { $exists: true } 필터가 샘플 문서를 제거하기 때문에 사용자가 제공 한 샘플에 대한 데이터가 반환되지 않습니다.

db.getCollection('Orders').aggregate([{ 
    $match: { 
     "Instructions.1": { 
      $exists: true 
     } 
    } 
}, { 
    $project: { 
     "_id": 0, 
     "UserId": "$User.EntityId", 
     "ItemName": { $arrayElemAt: [ "$Items.Details.ItemName", 0 /* first item! */] } 
    } 
}]) 
+0

정말 고마워요. 일치 검색 쿼리는 실제로 Items.1, 사과입니다. – NZJames

관련 문제