MongoDB 错误:<timeField> 必须存在并包含有效的 BSON UTC 日期时间值

问题描述 投票:0回答:2

我正在尝试使用 MongoDB Compass 中的“导入数据”按钮将现在变得非常简单的 JSON 导入到 MongoDB。

我从这个开始:

{"timestamp":"1728714859000","prio":"0"}
{"timestamp":"1728714859000","prio":"0"}

导致导入错误:

 {"name":"WriteError","message":"'timestamp' must be present and contain a valid BSON UTC datetime value","index":1,"code":2,"op: {"timestamp":"1728714859000","prio":"0","_id":"67397afef3e6b1d4dc9c2f44"}}

通过反复试验,我发现从时间戳中删除引号(如下所示)可以让我克服该错误。

{timestamp:"1728714859000","prio":"0"}
{timestamp:"1728714859000","prio":"0"}

现在我遇到了一个新错误,但仅在 GUI 中,其中指出:

Failed to import with the following error:

Parser cannot parse input: expected an object key

查看其他一些示例后,我找到了对

_id
的引用以及另一种执行时间戳的方法。

{
    "_id" : "5d11c815eb946a412ecd677d",
    "timestamp" : ISODate("2024-10-10T05:06:44.871Z"),
    "name" : "harry"
}

现在我收到错误:

Failed to import with the following error:

Parser cannot parse input: expected a value

按照另一个建议,我尝试使用 Python 插入数据:

import pymongo
import time

client = pymongo.MongoClient("mongodb://localhost:27017/")
db = client["sklogsdb"]
collection = db["sklogscol"]

record = {
    "timestamp": int(time.time() * 1000),
    "email": "[email protected]"
}

result = collection.insert_one(record)

这导致了同样的错误:

pymongo.errors.WriteError: 'timestamp' must be present and contain a valid BSON UTC datetime value, full error: {'index': 0, 'code': 2, 'errmsg': "'timestamp' must be present and contain a valid BSON UTC datetime value"}

我在这里做错了什么?

mongodb
2个回答
0
投票

经过大量实验,我发现我可以通过这样做使用 python 添加记录:

record = {
    "timestamp": datetime.datetime.now(),
    "email": "[email protected]"
}

查看 MongoDB 数据库中的记录,这是 MongoDB 所具有的格式,并且在导入 JSON 时有效:

{
  "timestamp": {
      "$date": "2024-11-18T20:54:41.916Z"
  },
  ...
}

-2
投票

出现这个问题是因为 MongoDB 在导入过程中需要有效的 JSON 和 BSON 结构,并且您的输入中存在一些语法和数据类型问题。另一件事是,像“1728714859000”这样的字符串不会被正确解释为时间戳。希望这解决了你的问题

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.