Search code examples
mongodbdatesubdocument

Mongodb find subdocument by month


I have a collection with following documents.

{
    "id":1,
    "url":"mysite.com",
    "views":
     [
       {"ip":"1.1.1.1","date":ISODate("2015-03-13T13:34:40.0Z")},
       {"ip":"2.2.2.2","date":ISODate("2015-03-13T13:34:40.0Z")},
       {"ip":"1.1.1.1","date":ISODate("2015-02-13T13:34:40.0Z")},
       {"ip":"1.1.1.1","date":ISODate("2015-02-13T13:34:40.0Z")}
     ]
},
{
    "id":2,
    "url":"mysite2.com",
    "views":
     [
       {"ip":"1.1.1.1","date":ISODate("2015-06-13T13:34:40.0Z")},
       {"ip":"2.2.2.2","date":ISODate("2015-08-13T13:34:40.0Z")},
       {"ip":"1.1.1.1","date":ISODate("2015-11-13T13:34:40.0Z")},
       {"ip":"1.1.1.1","date":ISODate("2015-11-13T13:34:40.0Z")}
     ]
}

How can I find documents have at least one view in June? I know how to do it use aggregation, (unwind > project > $month > match > group), but is there a way do it without aggregation? just use db.find()?


Solution

  • This one works:

    db.collection.find(
       {
          $expr: {
             $in: [6, { $map: { input: "$views", in: { $month: "$$this.date" } } }]
          }
       }
    )
    

    But there is not really a difference to the aggregation pipeline:

    db.collection.aggregate([
       {
          $match: {
             $expr: {
                $in: [6, { $map: { input: "$views", in: { $month: "$$this.date" } } }]
             }
          }
       }
    ])
    

    If you need to find several months, e.g. "June or November" use this one:

    db.collection.find(
       {
          $expr: {
             $gt: [0, { $size: { $setIntersection: [[6, 11], { $map: { input: "$views", in: { $month: "$$this.date" } } }] } }]
          }
       }
    )