简体   繁体   中英

using string for mongodb _id

I have a json document that I entered into my mongo db using the mongoimport command. I set it's _id to "MyDocId", looking at it in mongo, the _id is correctly set. in my C# code, I want to read this document using this _id:

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

I am getting an exception in the above code

You may need to use a Bson attribute on your property like so.

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

There is quite a good explanation of these attributes in this answered question

BsonId vs BsonRepresentation

ObjectId parse will only parse strings that have a valid format . In your case, if the document's _id is a string, you don't need to parse it as an ObjectId, just use the string value in your query.

Since version 2.9 of MongoDB.Driver you can also use built-in convention StringIdStoredAsObjectIdConvention

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM