1

I am developing a desktop application using windows forms c#, I've created an unique index named Id in my database.

But now I want it when I send a class with field 'Id' empty so the database gives it a unique value by its own.

I am sorry for not illustrating well and also the problem may seem easy, but I don't know how because i am still a beginner

Thanks in advance.

  • By default, MongoDB generates unique ObjectId for `_id` field. You can use it. For other cases, you need to [generate manually](https://stackoverflow.com/questions/50394800/how-to-use-auto-increment-field-in-mongo-c-sharp-driver-without-using-eval) – Valijon Apr 08 '20 at 07:38

1 Answers1

1

No need to create a unique index yourself. MongoDB creates a unique index on the _id field during the creation of a collection.

If an inserted document omits the _id field, the MongoDB driver automatically generates an ObjectId for the _id field. ObjectId essentially a timestamp plus random value.

In your models, you can map to _id field using attributes

[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
Pavel Shastov
  • 2,657
  • 1
  • 18
  • 26
  • Thanks for your response, But the problem here is that it is not human readable, i want an id that i can show in a list when i show a list of documents in my collection. – Khaled Mohamed Apr 10 '20 at 16:08
  • You can set _id manually, but there is no auto-increment functionality out of the box. You can do something like this: https://www.tutorialspoint.com/mongodb/mongodb_autoincrement_sequence.htm – Pavel Shastov Apr 10 '20 at 20:01