How do I use aggregation operators in a $match in MongoDB (for example $year or $dayOfMonth)?

前端 未结 3 1144
生来不讨喜
生来不讨喜 2021-02-12 16:22

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

3条回答
  •  说谎
    说谎 (楼主)
    2021-02-12 16:29

    Try this;

    db.createCollection("so");
    db.so.remove();
    db.so.insert([
    {
        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
    }
    ]);
    //db.so.find();
    
    db.so.ensureIndex({"created_date":1});
    db.runCommand({
        aggregate:"so",
        pipeline:[
            {
                $match: { // filter only those posts in september
                    created_date: { $gte: ISODate('2012-09-01'), $lt: ISODate('2012-10-01') }
                }
            },
            {
                $group: {
                    _id: null, // no shared key
                    comments: { $sum: "$comments" } // total comments for all the posts in the pipeline
                }
            },
    ]
    //,explain:true
    });
    

    Result is;

    { "result" : [ { "_id" : null, "comments" : 58 } ], "ok" : 1 }
    

    So you could also modify your previous example to do this, although I'm not sure why you'd want to, unless you plan on doing something else with month and year in the pipeline;

    {
        aggregate: 'posts',
        pipeline: [
         {$match: { created_date: { $gte: ISODate('2012-09-01'), $lt: ISODate('2012-10-01') } } },
         {$project:
              {
                   month : {$month:'$created_date'},
                   year : {$year:'$created_date'}
              }
         },
         {$match:
              {
                   month:9,
                   year: 2012
               }
         },
         {$group:
             {_id: '0',
              totalComments:{$sum:'$comments'}
             }
          }
        ]
     }
    

提交回复
热议问题