4

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

1

3 Answers 3

15

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

Sign up to request clarification or add additional context in comments.

1 Comment

How does it work with filter query builders? //Not fetching any documents collection.FindAsync(Builders<MyObj>.Filter.Where(x=>x.Id == "stringvalue")) //Gives syntax error (can't company ObjectId & string) collection.FindAsync(Builders<MyObj>.Filter.Where(x=>x.Id == ObjectId.Parse("stringvalue")))
7

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);

Comments

2

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.

2 Comments

I create a filter like so: Builders<PropertyHelperLookup>.Filter.Eq("_id", this._docId) and I am getting an exception
What is the exception?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.