我使用此代码来检索一些文档:
var client = new MongoClient(connectionString);
var database = client.GetDatabase(databaseName);
var collection = database.GetCollection<BsonDocument>(collectionName);
var json = "{created: {$gte: ISODate(\"2018-12-20T00:00:00.000Z\"), $lt:
ISODate(\"2018-12-21T00:00:00.000Z\")}}";
BsonDocument query = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonDocument>(json);
var documents = collection.Find(query).Limit(10);
结果如下所示:
{ "_id" : CSUUID("75c5634c-b64b-4484-81f5-5b213228e272"), ..., "created" : ISODate("2018-12-20T23:59:13.375Z") }
在尝试过滤_id时,我在检索同一文档时遇到问题.
以下是我尝试过的过滤器(使用与上面相同的代码)并且无法检索文档:
var json = "{ \"_id\" : \"75c5634c-b64b-4484-81f5-5b213228e272\" }";
var json = "{ \"_id\" : CSUUID(\"75c5634c-b64b-4484-81f5-5b213228e272\") }";
var json = "{ \"_id\" : new BinData(4, \"TGPFdUu2hESB9VshMijicg==\") }";
var json = "{ \"_id\" : BinData(4, \"TGPFdUu2hESB9VshMijicg==\") }";
var json = "{ \"_id\" : new BinData(3, \"TGPFdUu2hESB9VshMijicg==\") }";
var json = "{ \"_id\" : BinData(3, \"TGPFdUu2hESB9VshMijicg==\") }";
var json = "{ \"_id\" : { $eq: \"TGPFdUu2hESB9VshMijicg==\" } }";
var json = "{ \"_id\" : { $binary: \"TGPFdUu2hESB9VshMijicg==\", $type: 4 } }";
var json = "{ \"_id\" : { $binary: \"TGPFdUu2hESB9VshMijicg==\", $type: 3 } }";
注意,通过从guid获取base 64编码的字符串来检索TGPFdUu2hESB9VshMijicg ==,如下所示:
Convert.ToBase64String((new Guid("75c5634c-b64b-4484-81f5-5b213228e272")).ToByteArray())
没有任何查询抛出任何异常,但它们不返回任何文档.
解决方法:
在创建MongoClient()之前添加它解决了我的问题:
BsonDefaults.GuidRepresentation = GuidRepresentation.Standard;
看起来在C#端,MongoDB驱动程序将其解释为具有二进制子类型3的UUID.但是,保存在集合中的文档具有4的二进制子类型.
此外,在此更改后,检索到的文档显示“UUID()”而不是“CSUUID()”:
{ "_id" : UUID("75c5634c-b64b-4484-81f5-5b213228e272"), ..., "created" : ISODate("2018-12-20T23:59:13.375Z") }
经过一段时间,我不得不承认在网上搜索和测试许多理论,这一突破来自于浏览这篇文章:https://www.codeproject.com/Articles/987203/%2FArticles%2F987203%2FBest-Practices-for-GUID-data-in-MongoDB
摘自该链接:
MongoDB drivers usually store UUIDs as Binary fields with the legacy
0x03 subtype assigned by default. This configuration can be changed:C#:
You can override the driver’s default settings and configure it to use
the Binary 0x04 subtype by modifying the value of
BsonDefaults.GuidRepresentation:06002
You can also modify GuidRepresentation at
the server, database and collection level.
编辑:
这就是我最终用于json过滤器的内容:
var json = "{ \"_id\" : UUID(\"75c5634c-b64b-4484-81f5-5b213228e272\") }";
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。