【问题标题】:Query a month inside array MongoDB在数组MongoDB中查询一个月
【发布时间】:2020-12-07 05:47:27
【问题描述】:

我要解决的问题是使用 mongoose 的 find 模型函数查询文档数组。我的文档如下所示:

{
  name: "John",
  courses: [
    {
      name: "CS",
      enrolled: 2015-12-12T00:00:00.000+00:00,
      ...,
    },
    {
      name: "Math",
      enrolled: 2016-10-12T00:00:00.000+00:00,
      ...,
    },
    {
      name: "History",
      enrolled: 2017-09-12T00:00:00.000+00:00,
      ...,
    },
    ...,
  ]
}

所以,这里的问题是我正在尝试查询所有这些文档,其中数组中的一个子文档具有“已注册”字段,该字段与它所持有的日期的特定月份相匹配。例如,查找此人在 12 月(第 12 个月)注册课程的所有文件

我知道只要“注册”是文档中的日期字段,就可以执行以下操作。

{$expr: {$eq: [{$month: "$enroll"}, 12]}}

问题是日期字段在数组内并嵌入在子文档中。我想使用聚合管道,因为我需要使用 mongoose 的 find 模型函数检索整个文档。

关于如何进行的任何想法?谢谢!

【问题讨论】:

  • 你不能,因为当你在find()中使用位置运算符$时,它只会在结果check中给出一个匹配的find,你需要使用aggregate()
  • 好的,谢谢大家。最终改变了我的文档结构......

标签: mongodb mongoose mongodb-query


【解决方案1】:

由于您在查询中遇到了困难,您可以使用$filter 来消除不需要的对象。

{
    "$project": {
      name: 1,
      courses: {
        $filter: {
          input: "$courses",
          cond: {
            $eq: [
              "$$this.enrolled",
              "2016-10-12T00:00:00.000+00:00"
            ]
          }
        }
      }
    }
  }

工作Mongo playground

【讨论】:

  • 我不想使用聚合,因为我需要使用查找功能进行查询:/
  • 我认为没有聚合可能有一些方法
【解决方案2】:

如果您需要在检索整个文档的同时还执行匹配,那么聚合当然是可能的。

查询:

db.collection.aggregate([
  {
    $addFields: {
      coursesCopy: "$courses"
    }
  },
  {
    "$unwind": "$courses"
  },
  {
    "$match": {
      "$expr": {
        "$eq": [
          {
            "$month": "$courses.enrolled"
          },
          12
        ]
      }
    }
  },
  {
    $group: {
      _id: "$_id",
      courses: {
        $first: "$coursesCopy"
      }
    }
  }
]);

Playground link -Demo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-14
    • 1970-01-01
    • 2021-11-12
    • 1970-01-01
    • 2013-08-30
    • 2018-07-23
    • 1970-01-01
    • 2013-12-04
    相关资源
    最近更新 更多