4

When I insert to Mongo, I do not want to define _id, but I do want to READ _id. When using an object such as

public class MyClass
    {
        public Object _id { get; set;}
        public String propery1 { get; set; }
    }

I am writing null _id if I do something like

this.myobj.property1 = "Useless info";    
SafeModeResult result = this.uploads.Insert(uploadedfilecanonical, SafeMode.True);

Do I need to create separate class types for query binding vs. insert binding, where insert does not define _id property but queryable does?

2 Answers 2

4

I'm not really understanding your question, so I'll do my best here. If you do an insert, if the _id is null, it will persist null. If you use Save, it will create an identifier for you if one doesn't exist. However, you are using an Object as your id, which is rather odd. We suggest you use an ObjectId, an integer, a Guid, or something.

In addition, you can use a property called "Id" instead of the non-conventional _id for a .NET class. Alternatively, you can use an attribute to denote the id or you can create a convention to apply a common pattern. I highly suggest reading the tutorial for more information.

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

3 Comments

thank you. I also see from c# driver site: "_id" is the name of the field as stored in the database (normally the name of the field in the database is exactly the same as the name of the field or property in your domain class, but Id is an exception and is mapped to "_id" in the database).
Yes, it is a configurable exception that is possible to change using a different convention.
@CraigWilson These tutorials do not exists anymore. Is there an updated reference?
0

Only ObjectId and Guid works here as a type of Id property. You can name property without underscore (and without [BsonId] attribute).

ObjectId is natural for mongo, server will create it and respond with it, this the fastest way, AFAIU. Guid is natural for .NET but Mongo Drivers at the client side will generate this ID and encode it for mongo. The last 2 rows is how .Net Guid stored in mongo. First several rows is natural mongo ObjectId. enter image description here

as long as you just have to provide a reference somewhere, ObjectId structure should works for you.

But if you serializing Id you might see unpleasant results. It is possible to change BsonRepresentation and go with string using attribute e.g. like this:

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

Comments

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.