MongoDB,尝试导入已使用 TypeNameHandling.Objects 序列化的 json

本文关键字:Objects TypeNameHandling 序列化 json 导入 MongoDB | 更新日期: 2023-09-27 18:30:45

我在尝试将我的 json 导入 mongodb 时收到此错误。

2016-01-15T14:57:09.682-0800 插入文档时出错:文档不能有 $ 带前缀的字段名称:$type

使用 Json.Net 序列化 json

 var settings = new JsonSerializerSettings();
settings.TypeNameHandling = TypeNameHandling.Objects;
string output = JsonConvert.SerializeObject(o, Formatting.Indented, settings);

MongoDB,尝试导入已使用 TypeNameHandling.Objects 序列化的 json

请参阅 MongoDB 文档,其中讨论了对字段名称的限制。

Field names cannot contain dots (i.e. .) or null characters, and they must 
not start with a dollar sign (i.e. $).

如果您使用 Mongo shell 进行导入,则可能需要将$type更改为其他内容。

或者,可以使用 C# 驱动程序导入文档,它将自动处理序列化具体类型名称。