2017-12-28 15 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を追加することを検討すべきであるように、しかしそれほど効率的ではありません。

関連する問題