created_date属性を持つドキュメントでいっぱいのコレクションがあります。これらのドキュメントを集約パイプラインを介して送信し、いくつかの作業を行いたいと思います。理想的には、インデックスを利用できるように、他の作業を行う前に$ matchを使用してそれらをフィルタリングしたいのですが、新しい$ year / $ month /$dayOfMonth演算子を使用する方法がわかりません。 $match式。
$ project操作で演算子を使用する方法のいくつかの例が浮かんでいますが、パイプラインの最初のステップとして$ projectを配置すると、インデックスにアクセスできなくなるのではないかと心配しています(MongoDBのドキュメントによるとインデックスを利用するには、最初の式は$ matchでなければなりません)。
サンプルデータ:
{
post_body: 'This is the body of test post 1',
created_date: ISODate('2012-09-29T05:23:41Z')
comments: 48
}
{
post_body: 'This is the body of test post 2',
created_date: ISODate('2012-09-24T12:34:13Z')
comments: 10
}
{
post_body: 'This is the body of test post 3',
created_date: ISODate('2012-08-16T12:34:13Z')
comments: 10
}
これを集計パイプラインで実行して、9月に行われたすべての投稿に対する合計コメントを取得したいと思います。
{
aggregate: 'posts',
pipeline: [
{$match:
/*Can I use the $year/$month operators here to match Sept 2012?
$year:created_date : 2012,
$month:created_date : 9
*/
/*or does this have to be
created_date :
{$gte:{$date:'2012-09-01T04:00:00Z'},
$lt: {$date:'2012-10-01T04:00:00Z'} }
*/
},
{$group:
{_id: '0',
totalComments:{$sum:'$comments'}
}
}
]
}
これは機能しますが、一致すると、より複雑なクエリのインデックスにアクセスできなくなります。
{
aggregate: 'posts',
pipeline: [
{$project:
{
month : {$month:'$created_date'},
year : {$year:'$created_date'}
}
},
{$match:
{
month:9,
year: 2012
}
},
{$group:
{_id: '0',
totalComments:{$sum:'$comments'}
}
}
]
}