问题
我有一组动态数据。我想像这样找回它:
{
_id: "58b454f20960a1788ef48ebb"
...
}
尝试
以下是无效的方法列表:
这个
await resources = _database.GetCollection<BsonDocument>("resources")
.Find(Builders<BsonDocument>.Filter.Empty)
.ToListAsync();
return Ok(resources);
产量
[[{"name":"_id","value":{"bsonType":7,"timestamp":1488213234,"machine":614561,"pid":30862,"increment":16027323,"creationTime":"2017-02-27T16:33:54Z","rawValue":{"timestamp":1488213234,"machine":614561,"pid":30862,"increment":16027323,"creationTime":"2017-02-27T16:33:54Z"},"value":{"timestamp":1488213234,"machine":614561,"pid":30862,"increment":16027323,"creationTime":"2017-02-27T16:33:54Z"}}}]]
这个
await resources = _database.GetCollection<BsonDocument>("resources")
.Find(Builders<BsonDocument>.Filter.Empty)
.ToListAsync();
return Ok(resources.ToJson());
产量
[{ "_id" : ObjectId("58b454f20960a1788ef48ebb"), ... }]
这个
await resources = _database.GetCollection<BsonDocument>("resources")
.Find(Builders<BsonDocument>.Filter.Empty)
.ToListAsync();
return Ok(resources.ToJson(new JsonWriterSettings() { OutputMode = JsonOutputMode.Strict }));
产量
[{ "_id" : { "$oid" : "58b454f20960a1788ef48ebb" }, ... }]
这个
await resources = _database.GetCollection<BsonDocument>("resources")
.Find(Builders<BsonDocument>.Filter.Empty)
.ToListAsync();
return Ok(Newtonsoft.Json.JsonConvert.SerializeObject(resources));
产量
"Newtonsoft.Json.JsonSerializationException: Error getting value from 'AsBoolean' on 'MongoDB.Bson.BsonObjectId'. ---> System.InvalidCastException: Unable to cast object of type 'MongoDB.Bson.BsonObjectId' to type 'MongoDB.Bson.BsonBoolean'
将 BsonDocument
更改为 dynamic
会产生相同的结果。
我也尝试过根据 the docs 注册一个序列化程序。我真的很喜欢这个解决方案,因为我总是希望我的 ObjectId
格式合理,而不是无法使用。如果可能的话,我想让这个工作。
这个
_client = new MongoClient(clientSettings);
_database = _client.GetDatabase(_settings.DatabaseName);
BsonSerializer.RegisterSerializer(new ObjectIdSerializer());
...
class ObjectIdSerializer : SerializerBase<ObjectId>
{
public override ObjectId Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
{
return context.Reader.ReadObjectId();
}
public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, ObjectId value)
{
context.Writer.WriteString(value.ToString());
}
}
对上述任何结果都没有影响。
最佳答案
保存到 MongoDB 时使用 BsonDocument
在尝试了许多不同的配置之后,我能够使用连接器正确保存真正动态文档的唯一方法是将对象解析为 BsonDocument
s。
public ActionResult Post([FromBody]JObject resource)
{
var document = BsonDocument.Parse(resource.ToString(Formatting.None));
DbContext.Resources.InsertOne(document);
}
使用 JSON.Net 注册 BsonDocument
序列化程序
上述方法最初的问题是,当调用 ToJson()
时,ISODate
和 ObjectId
对象将被序列化为对象,这是不受欢迎的。在撰写本文时,似乎没有任何可扩展点来覆盖此行为。逻辑被烘焙到 MongoDB.Bson.IO.JsonWriter
class ,并且您不能为 BsonValue
类型注册 BsonSerializer
:
MongoDB.Bson.BsonSerializationException: A serializer cannot be registered for type BsonObjectId because it is a subclass of BsonValue.
在撰写本文时,我发现的唯一解决方案是显式自定义 JSON.Net 转换器。 MongoDB C# Lead Robert Stam已创建 an unpublished library for this社区成员 Nathan Robinson 拥有 ported to .net-core. . I've created a fork正确序列化 ObjectId 和 ISODate 字段。
我根据他们的工作创建了一个 NuGet 包。要使用它,请在您的 .csproj
文件中包含以下引用:
<PackageReference Include="MongoDB.Integrations.JsonDotNet" Version="1.0.0" />
然后,显式注册转换器:
Startup.cs
using MongoDB.Integrations.JsonDotNet.Converters;
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().AddJsonOptions(options =>
{
// Adds automatic json parsing to BsonDocuments.
options.SerializerSettings.Converters.Add(new BsonArrayConverter());
options.SerializerSettings.Converters.Add(new BsonMinKeyConverter());
options.SerializerSettings.Converters.Add(new BsonBinaryDataConverter());
options.SerializerSettings.Converters.Add(new BsonNullConverter());
options.SerializerSettings.Converters.Add(new BsonBooleanConverter());
options.SerializerSettings.Converters.Add(new BsonObjectIdConverter());
options.SerializerSettings.Converters.Add(new BsonDateTimeConverter());
options.SerializerSettings.Converters.Add(new BsonRegularExpressionConverter());
options.SerializerSettings.Converters.Add(new BsonDocumentConverter());
options.SerializerSettings.Converters.Add(new BsonStringConverter());
options.SerializerSettings.Converters.Add(new BsonDoubleConverter());
options.SerializerSettings.Converters.Add(new BsonSymbolConverter());
options.SerializerSettings.Converters.Add(new BsonInt32Converter());
options.SerializerSettings.Converters.Add(new BsonTimestampConverter());
options.SerializerSettings.Converters.Add(new BsonInt64Converter());
options.SerializerSettings.Converters.Add(new BsonUndefinedConverter());
options.SerializerSettings.Converters.Add(new BsonJavaScriptConverter());
options.SerializerSettings.Converters.Add(new BsonValueConverter());
options.SerializerSettings.Converters.Add(new BsonJavaScriptWithScopeConverter());
options.SerializerSettings.Converters.Add(new BsonMaxKeyConverter());
options.SerializerSettings.Converters.Add(new ObjectIdConverter());
});
}
}
现在,您可以使用默认序列化程序进行序列化:
return Created($"resource/{document["_id"].ToString()}", document);
关于c# - .NET Core 中的 Mongo C# 驱动程序和 ObjectID JSON 字符串格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44085267/