gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 10:37:41 24 4
gpt4 key购买 nike

我有一个包含如下条目的 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 所问,这是一个玩具示例及其工作原理:这是一个时间戳字段作为字符串的示例集合

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

关于mongoDB多级嵌套字符串转换为日期对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53831053/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com