【问题标题】:Mongodb find subdocument by monthMongodb按月查找子文档
【发布时间】:2021-07-05 09:37:53
【问题描述】:

我有一个包含以下文档的集合。

{
    "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")}
     ]
}

我如何才能找到在 6 月至少有一次查看的文档?我知道如何使用聚合(展开 > 项目 > $month > 匹配 > 组),但是有没有不聚合的方法呢?只使用 db.find()?

【问题讨论】:

  • 您是指某个特定年份的六月还是六月?

标签: mongodb date subdocument


【解决方案1】:

这个有效:

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

但聚合管道并没有真正的区别:

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

如果您需要查找几个月,例如“六月或十一月”使用这个:

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

【讨论】:

  • 您在聚合管道中尝试过{allowDiskUse: true} 吗?否则,您真的必须使用 { $month: "$views.date" } 更新集合并在其上创建索引
猜你喜欢
  • 2015-05-03
  • 2017-04-15
  • 1970-01-01
  • 2021-07-25
  • 2016-08-25
  • 2016-04-18
  • 1970-01-01
  • 2021-11-20
  • 1970-01-01
相关资源
最近更新 更多