我有一个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字段转换为日期时(它存储在mongoDB中名为“ collection”的集合中),并为该字段创建一个名为“ 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
期待任何帮助或提示,以使其正常工作。预先感谢!
按照安东尼的要求,这是一个玩具示例,以及它如何工作: 这是一个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") }
这是我想获得的
答案 0 :(得分:1)
您的日期在数组内,这就是它引发错误Unsupported conversion from array to date
的原因。
您需要使用$map
遍历features数组,然后需要添加从字符串转换为日期的字段timeMongo
db.collection.aggregate([
{ "$addFields": {
"features": {
"$map": {
"input": "$features",
"in": {
"$mergeObjects": [
"$$this",
{
"timeMongo": {
"$toDate": "$$this.properties.timeStamp"
}
}
]
}
}
}
}}
])