mongoDB 多级嵌套字符串转换为日期对象

mongoDB multiple-levels nested string conversion to date objects

我有一个 mongoDB 包含这样的条目:

{ "_id" : ObjectId("5bdb6a44d9b2d4645509db2e"), 
"crs" : { "type" : "name", 
         "properties" : { "name" : "urn:ogc:def:crs:OGC:1.3:CRS84" } },
"type" : "FeatureCollection", 
"features" : [ { "geometry" : { "type" : "Point", "coordinates" : [ 45,66 ] }, 
"type" : "Feature", 
"id" : 50,  
"properties" : { "fogClass" : 0, "_note" : "movable", "fileLocation" : "blah.jpg", "timeStamp" : "2018-11-01 14:51:00", "predFALSE" : 0.998167, "ipAddr" : "http://abcd.ef", "longitude" : "45", "predTRUE" : 0.001833, "cameraID" : "IDABC", "originalPath" : "originalBlah.jpg", "location" : "location1", "latitude" : "66" } } ] }

我想执行基于时间戳的查询,但我知道时间戳必须是 mongoDB 时间戳对象,而不是现在的字符串。

我发现此函数可能有助于转换为 mongoDB 日期对象 https://docs.mongodb.com/manual/reference/operator/aggregation/toDate/ 并且它适用于具有非常简单(非嵌套)JSON 结构的玩具示例.

当我执行相同的操作以将数据集中的时间戳字段转换为日期(它存储在名为 "collection" 的集合中的 mongoDB 中)并为此创建一个名为"timeMongo"如下:

db.collection.aggregate({$addFields:{timeMongo:{"$toDate":"$features.properties.timeStamp"}}})

我收到以下错误:

 [js] Error: command failed: {
    "ok" : 0,
    "errmsg" : "Unsupported conversion from array to date in $convert with no onError value",
    "code" : 241,
    "codeName" : "ConversionFailure"
} : aggregate failed :
_getErrorWithCode@src/mongo/shell/utils.js:25:13
doassert@src/mongo/shell/assert.js:18:14
_assertCommandWorked@src/mongo/shell/assert.js:534:17
assert.commandWorked@src/mongo/shell/assert.js:618:16
DB.prototype._runAggregate@src/mongo/shell/db.js:260:9
DBCollection.prototype.aggregate@src/mongo/shell/collection.js:1062:12
@(shell):1:1

期待任何帮助或提示如何让它发挥作用。提前致谢!


正如 Anthony 所问,这是一个玩具示例及其工作原理: 这是一个 timeStamp 字段作为 string

的示例集合
db.testColl3.find()
{ "_id" : ObjectId("5c1e7fc6e9739a0c2ef3d7fc"), "item" : "card", "qty" : 15, "timeStamp" : "2018-12-20 08:00:00" }

然后一旦我发出命令:

db.testColl3.aggregate({$addFields:{timeMongo:{$toDate:"$timeStamp"}}})

我收到这样的回复:

{ "_id" : ObjectId("5c1e7fc6e9739a0c2ef3d7fc"), "item" : "card", "qty" : 15, "timeStamp" : "2018-12-20 08:00:00", "timeMongo" : ISODate("2018-12-20T08:00:00Z") }

这是我想要得到的

您的日期在数组内,这就是它抛出错误的原因 Unsupported conversion from array to date

您需要使用 $map 遍历要素数组,然后需要添加从字符串转换为日期的字段 timeMongo

db.collection.aggregate([
  { "$addFields": {
    "features": {
      "$map": {
        "input": "$features",
        "in": {
          "$mergeObjects": [
            "$$this",
            {
              "timeMongo": {
                "$toDate": "$$this.properties.timeStamp"
              }
            }
          ]
        }
      }
    }
  }}
])