1

We are using MongoDB C#.NET Driver to insert entry as below:

var JSON = "{ 'UserName': '" + "Roy" + "', 'PasswordHash' : '" + "123" + "' }";

            var document = BsonSerializer.Deserialize<BsonDocument>(JSON);

            await collection.InsertOneAsync(document);

In MongoDb, it goes with

_id:ObjectId("5e54f9ea045dba534831a1a2")

Which gives issues when retrieved and tried to convert into json. How can I set the _id from C# code itself?

2
  • possible duplicate? stackoverflow.com/questions/60264331/… Commented Mar 4, 2020 at 13:49
  • _id in mongo is simply a hex string, could you just create a uuid / hex in c#, assign it to your domain then save it? not sure how good practice this is though. also why are you inserting json directly into your db and not creating a dedicated domain object? docs.mongodb.com/manual/reference/method/ObjectId Commented Mar 4, 2020 at 13:50

1 Answer 1

1

The _id is always generated on a client side - the driver does that behind the scenes when you run .Insert() or .Save(). You can do that manually by running:

document["_id"] = ObjectId.GenerateNewId().ToString();
Sign up to request clarification or add additional context in comments.

2 Comments

I tried that but the below got inserted: _id:ObjectId("5e60abdd89b5880a48464df0") We want only _id:"5e60abdd89b5880a48464df0" to go into the MongoDb.
The solution in my case was : document["_id"] = ObjectId.GenerateNewId().ToString(); If you could put it as the answer, I would mark it as the answer.

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.