简体   繁体   中英

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()?

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, eg "June or November" use this one:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM