我只是在学习MongoDB,而且我很喜欢它。直到我发现了这一期“储存指南”。一件看似简单的事情变得相当困难。我已经阅读了GuidRepresentation部分,并看到标准的方法是将其存储为二进制子类型4 (Binary('iWoBDYb9IEOJZL4XKf1JDw==', 3))。我真的希望能够插入Guid,在Compass和shell中查看Guid,并能够在Guid上进行筛选。在效率高的情况下能做到这一点吗?
对于具有属性的PoC,我有一个简单的用户类:
public Guid? ExternalId { get; set; }
public String Name { get; set; }
public String? Address { get; set; }
public Int32? Age { get; set; }
public String? HairColor { get; set; }在创作方面,我会:
user.ExternalId = Guid.NewGuid();
var dbClient = new MongoClient("mongodb://localhost");
var database = dbClient.GetDatabase("testDb");
var collection = database.GetCollection<BsonDocument>("users", _mongoCollectionSettings);
var bsonDocument = model.ToBsonDocument();
await collection.InsertOneAsync(bsonDocument);在Program.cs中:
BsonSerializer.RegisterSerializer(new GuidSerializer(GuidRepresentation.Standard));它插入的一切都非常好,除了在MongoDB罗盘和shell中,ExternalId显示为Binary('iWoBDYb9IEOJZL4XKf1JDw==', 3)。能够在Compass中看到实际的Guid值,而无需将二进制值复制到控制台应用程序来转换它,这一点非常重要和有用,特别是对调试而言。
发布于 2022-08-07 16:56:14
尽管以下内容给出了一条警告消息,指出:
'BsonDefaults.GuidRepresentationMode‘过时了:“该属性将在以后的版本中删除。”
你确实需要加上:
BsonDefaults.GuidRepresentationMode = GuidRepresentationMode.V3;(在我的例子中是Program.cs),根据文档。(https://mongodb.github.io/mongo-csharp-driver/2.17/reference/bson/guidserialization/guidrepresentationmode/guidrepresentationmode/)我现在可以在MongoDB Compass中查看Guid UUID('976817aa-25f7-46e0-979d-2240a39e699f')。
https://stackoverflow.com/questions/73180260
复制相似问题