【问题标题】:Mongodb: Is it possible to create ISODate field in Aggregation Pipeline from an existing string field?Mongodb:是否可以从现有的字符串字段在聚合管道中创建 ISODate 字段?
【发布时间】:2018-04-10 18:32:04
【问题描述】:

我试图限制一个集合上的结果集,该集合不幸地将“date_modified”字段设置为字符串。尝试投影此字段时,我收到“无效的 ISO 日期”错误。代码是:-

var testDateString = "2018-03-10T00:00:000Z"

db.getCollection('updates').aggregate([
{$match:{"summary_display_tags.Source": "whatever" }},
{$project:{_id:0, source_id:"$source_id", update_date: { $concat: [ {$substr: [ "$date_modified", 0, 10 ]},"T00:00:000Z"]}  }}
, {$project:{_id:0, source_id:"$source_id", update_date_string: "$update_date"
, updated_date: {$add: [new ISODate("$update_date")] }
//, updated_date2: {$add: [new ISODate(testDateString)] }
}}
])

我不明白的是,如果我尝试使用变量字符串(即updated_date2)进行投影,它可以正常工作,但是我在尝试根据投影字段字符串添加日期时遇到错误...

我们这里是 3.2,所以我没有 $dateToString 的选项。谢谢!

【问题讨论】:

    标签: mongodb aggregation-framework


    【解决方案1】:

    为了获得梦寐以求的“风滚草”徽章,在没有收到任何回复的情况下,我想我会发布我所做的事情,以防其他人遇到同样的问题......

    由于在聚合管道中将字符串字段强制转换为日期字段似乎是不可能的,所以我在 php 中完成了工作:-

    $greatestAcceptableDate = new MongoDate(strtotime( "-14 days"));
    
    $cursor = db.getCollection('updates').find(array("summary_display_tags.Source"=> "whatever"));
    foreach ($cursor as $rec){   
       $recordTS = $this->buildTimestamp(strtotime(str_replace('-','/',substr($rec['date_modified'],0,10)).' 00:00:00'));
       if ($recordTS < $greatestAcceptableDate){
       db.getCollection('updates').remove("_id": $rec('_id'));
    }
    

    在这里这样做给了我可比较的日期字段,考虑到 mongo 聚合查询的问题,这似乎是不可能的......

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-12
      • 2018-08-06
      • 2019-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多