代码之家  ›  专栏  ›  技术社区  ›  Rockwell Rice

查询嵌套数组中的日期范围不工作

  •  0
  • Rockwell Rice  · 技术社区  · 4 年前

    db.collection('' + site_id + '_page_visits').find({created_at: {"$gte": new Date("" + date + "T00:00:00.000Z"), "$lte": new Date("" + date + "T23:59:59.999Z")}}).toArray(...
    

    但是,我需要在第二个查询中检查的日期嵌套在 call_to_action_responses

    db.collection('' + site_id + '_leads').find({"call_to_action_responses.response_date": {$gte: new Date("" + date + "T00:00:00.000Z"), $lte: new Date("" + date + "T23:59:59.999Z")}, "call_to_action_responses.page_url": {$not: regex}, "call_to_action_responses.page_url": {$ne: ''} }).toArray(...
    

    使用该代码,它返回所有匹配的文档 $lte 只有它似乎忽视了 $gte 过滤器的一部分,在第一个示例中起作用。

    {
      _id: ObjectId("XXxXXxxxxxXXxXx"),
      cookie: "xxcXXXXxxx-xxxXXXx-XXXXxx",
      updated_at: ISODate("2016-09-20T01:31:56.677Z"),
      created_at: ISODate("2015-04-22T08:32:34.864Z"),
      call_to_action_responses: [
        {
          response_date: ISODate("2015-04-22T08:32:34.863Z"),
          page_version: "1",
          template_response_path_base: "page_path",
          page_url: "http://www.webiste.com/about",
          page_id: ObjectId("5527d6c40de2c02a0b0000f2"),
          email: "user_email_at@email.com",
          lead_data: {
            phone: "XXXXXXXXX",
            viewed_assets: "This_Asset",
            campaign_medium: "",
            campaign_content: "",
            first_name: "first",
            last_name: "last",
            campaign_source: "",
            campaign_name: "",
            company: "Test Company",
            title: ""
           },
          _id: ObjectId("XXXXxxXXxXXxXXXX"),
          name: "View ",
          target_url: "http://www.webiste.com/about"
        }
      ]
    }
    

    有人能看出我做错了什么吗?我让我知道这个语法,因为我似乎无法得到它拨入。谢谢你的帮助!

    0 回复  |  直到 4 年前
        1
  •  0
  •   ngShravil.py    4 年前

    以下查询将很有帮助:

    db.collection.aggregate([
      {
        $addFields: {
          call_to_action_responses: {
            $filter: {
              input: "$call_to_action_responses",
              as: "i",
              cond: {
                $and: [
                  {
                    $gte: [
                      "$$i.response_date",
                      new Date("2015-03-23T00:00:00.000Z")
                    ]
                  },
                  {
                    $lte: [
                      "$$i.response_date",
                      new Date("2015-06-23T23:59:59.999Z")
                    ]
                  }
                ]
              }
            }
          }
        }
      }
    ])
    

    MongoPlayGroundLink