Mongodb按月查找子文档

问题描述

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

object Foo {
  def main(args: Array[String]): Unit = {
    val a: Bar[_] = Foo(3)
    val b: Bar[_] = Foo(2)
    a.baz(b) // This call is invalid
  }
}

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

解决方法

这个有效:

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

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

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

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

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