2

我有一个 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 结构。

当我执行相同的操作将数据集中的 timeStamp 字段转换为日期时(它存储在名为“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 字段作为字符串的示例集合

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") }

这就是我想要获得的

4

1 回答 1

2

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

您需要使用迭代特征数组$map,然后需要添加timeMongo从字符串转换为日期的字段

db.collection.aggregate([
  { "$addFields": {
    "features": {
      "$map": {
        "input": "$features",
        "in": {
          "$mergeObjects": [
            "$$this",
            {
              "timeMongo": {
                "$toDate": "$$this.properties.timeStamp"
              }
            }
          ]
        }
      }
    }
  }}
])
于 2018-12-23T06:20:28.393 回答