2017-12-28 17 views
0

"구매"컬렉션이 주어지면 각 사람의 을 가장 최근의 구입할 수 있습니까?MongoDB의 여러 필드에서 가장 최근의 레코드를 얻으십시오

각 사람은 first_namelast_name에서 고유합니다.

예 컬렉션 :

[ 
    { 
    first_name: "Don", 
    last_name: "Foobar", 
    date: 11111111, // The unix timestamp of purchase 
    purchase: {...} 
    }, 
    { 
    first_name: "Don", 
    last_name: "Foobar", 
    date: 22222222, 
    purchase: {...} 
    }, 
    { 
    first_name: "James", 
    last_name: "McManason", 
    date: 12341234, 
    purchase: {...} 
    } 
    ... 
] 

내가 무엇을 시도했다 :

코드를 아래이 (슈퍼 서브 최적)를 통해 반복하는 사람들의 이름의 모음 주어진 일 것입니다 :

collection 
    .find({ first_name: "Tom", last_name: "Brady" }) 
    .sort({ date: -1 }) 
    .limit(1) 

collection 
    .find({ first_name: "James", last_name: "Foo" }) 
    .sort({ date: -1 }) 
    .limit(1) 

collection 
    .find({ first_name: "Marcia", last_name: "Bar" }) 
    .sort({ date: -1 }) 
    .limit(1) 

답변

1

그래서 좀 더 일반적인 해결책이 필요합니까? 그래서 다음이 시도하는 경우 : 당신의 전체 컬렉션을 정렬

db.collection.aggregate([ 
{ $sort: { date: -1}}, // sort by date descending 
{ 
    $group: { 
    _id: { firstName: "$first_name", lastName: "$last_name"}, // group by 
                  // first and last name 
    purchase: {$first: "$purchase"} // get the first purchase since the documents are 
            // ordered by date and the first is also the latest 
    } 
} 
]) 

을 당신이 $sort 전에 $match을 추가하는 것을 고려한다, 그래서하지만 그렇게 효율적이지 않습니다.