Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (47.6k points)

I have a collection full of documents with a created_date attribute. I'd like to send these documents through an aggregation pipeline to do some work on them. Ideally, I would like to filter them using a $match before I do any other work on them so that I can take advantage of indexes however I can't figure out how to use the new $year/$month/$dayOfMonth operators in my $match expression.

There are a few examples floating around of how to use the operators in a $project operation but I'm concerned that by placing a $project as the first step in my pipeline then I've lost access to my indexes (MongoDB documentation indicates that the first expression must be a $match to take advantage of indexes).

Sample data:

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 

}

I'd like to run this through an aggregation pipeline to get the total comments on all posts made in September

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'} 

}

This works but the match loses access to any indexes for more complicated queries:

aggregate: 'posts',

pipeline: [ 

{$project: 

month : {$month:'$created_date'}, 

year : {$year:'$created_date'} 

}, 

{$match: 

month:9, 

year: 2012 

}, 

{$group: 

{_id: '0',

 totalComments:{$sum:'$comments'} 

}

1 Answer

0 votes
by (106k points)

To use aggregation operators in a $match in MongoDB you can use the below-mentioned code:-

aggregate: 'posts', 

pipeline: [ 

{$match: { 

created_date : 

{$gte:{$date:'2012-09-01T04:00:00Z'}, 

$lt: {date:'2012-10-01T04:00:00Z'} 

}} 

 } 

}, 

{$group: 

{_id: '0', 

totalComments:{$sum:'$comments'} 

}

Related questions

0 votes
1 answer
asked Feb 9, 2020 in Web Technology by ashely (50.2k points)
0 votes
3 answers
0 votes
1 answer
asked Mar 14, 2020 in Web Technology by ashely (50.2k points)
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...