4

ドキュメントにdateフィールドがあり、最初と最後に出現するドキュメントを集計で取得したいとします。$groupおよび$minまたはを使用すると$max、日付自体を簡単に取得できます。例:

db.mycollection.aggregate([
  { $group: {
      _id: 1, // for the example say I'm grouping them all ... 
      first: { $min: "$date" },
      result: { $push: { ... } } // ... and returning them all
  }}
])

これにより、次のような結果が返されます。

{ _id: 1, first: ISODate(...), result: [...] }

しかし、私が欲しいのは最初のデートではなく、最初のデートの結果です。パイプラインを使用してこれをどのように取得しますか?

後で配列をスキャンして、日付が一致するオブジェクトを探していましたが、これは機能するようですが、不適切なオブジェクトに遭遇する前に、これを行う適切な$project方法があるかどうかを確認したいと思いました。 。

4

1 に答える 1

7

ここを使用$firstして、ソートされたセットの最初のものを取得できます(http://docs.mongodb.org/manual/reference/aggregation/first/#_S_first):

db.mycollection.aggregate([
  { $group: {
      _id: 1, // for the example say I'm grouping them all ... 
      first: { $first: "$date" },
      result: { $push: { ... } } // ... and returning them all
  }}
])

これにより、$ groupの並べ替えにインデックスを使用して、パフォーマンスを向上させることもできます。

于 2013-02-01T21:12:40.563 に答える