簡體   English   中英

使用字符串作為 mongodb _id

[英]using string for mongodb _id

我有一個 json 文檔,我使用 mongoimport 命令將它輸入到我的 mongo 數據庫中。 我將它的 _id 設置為“MyDocId”,在 mongo 中查看它,_id 設置正確。 在我的 C# 代碼中,我想使用這個 _id 閱讀這個文檔:

ObjectId id = ObjectId.Parse("MyDocId");

我在上面的代碼中遇到異常

您可能需要像這樣在您的屬性上使用 Bson 屬性。

[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }

在這個回答的問題中對這些屬性有很好的解釋

BsonId 與 BsonRepresentation

ObjectId parse 將只解析具有有效格式的字符串。 在您的情況下,如果文檔的_id是字符串,則無需將其解析為 ObjectId,只需在查詢中使用字符串值即可。

MongoDB.Driver 2.9 版開始,您還可以使用內置約定StringIdStoredAsObjectIdConvention

        var pack = new ConventionPack
        {
            new StringIdStoredAsObjectIdConvention()
        };

        ConventionRegistry.Register("Custom Convention", pack, t => true);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM