提问者:小点点

Mongoose聚合管道日期大于使用bson变量的查询


实际上,我是在尝试了之前的问题答案后提出这个问题的。但是,我没有找到任何线索,这就是我问的原因

试图实现:

在猫鼬聚合中,我正在使用流水线聚合,通过以下查询从集合中获取文档

$match: {
  $and: [
    {
      $expr: {
        $eq: ["$device_id", "$$device_id"]
      }
    },
    {
      date: {
        "$gte": "$billing_cycle_startdate",
        "$lte": endOfDay
      }
    }
  ]
}

billing_cycle_startdate将是:2020-12-31T00:00:00.000Z通过以下查询

{
  $addFields: {
    billing_cycle_startdate: {
      $concat: [
        year, "-", month, "-", "$device_details.billing_cycle"
      ]
    },
  }
},
{ $set: { billing_cycle_startdate: {  $toDate: "$billing_cycle_startdate" } }},

但是这个查询返回空结果

如果我跑

{
  date: {
    "$gte": new Date("2020-12-31T00:00:00.000Z"),
    "$lte": endOfDay
  }
}

它按预期返回结果

有没有其他方法可以在不使用new Date()函数的情况下将2020-12-31T00:00:00.000Z转换为可查询格式,并且还想知道2020-12-31T00:00:00.000Z和new Date(“2020-12-31T00:00:00.000Z”)之间的区别

还有其他方法可以实现此查询吗??

提前感谢…!


共1个答案

匿名用户

终于,经过几天的煎熬,我发现我的质疑有什么问题

我只是忘记了在我的管道中使用let语法来指定一个billing_cycle_startdate的变量,忘记了在管道字段阶段使用它

流水线不能直接访问输入文档字段。相反,首先为输入文档字段定义变量,然后在流水线中引用阶段中的变量。

更多信息:点击这里

然后我更改了我的查询如下

   {
                $lookup: {
                    from: "name",
                    let: {
                        device_id: "$budget.device",
                        billing_cycle_startdate: "$billing_cycle_startdate"
                    },
                    pipeline: [
                        {
                            $match: {
                                $and: [
                                    {
                                        $expr: {
                                            $eq: ["$device_id", "$$device_id"]
                                        }
                                    },
                                    {
                                        $and: [
                                            {
                                                $expr: {
                                                    $gte: ["$date", "$$billing_cycle_startdate"],
                                                },
                                            },
                                            {
                                                $expr: {
                                                    $lte: ["$date", endOfDay],
                                                }
                                            }
                                        ]
                                    }
                                ]
                            }
                        }
                    ],
                    as: "dailyenergylogs"
                }
            },

相关问题