4

I was able to successfully insert a new document using the following code but I was not able to get the _id of the newly inserted document.

After the insert, user is null. Thank you!

MongoServer server = MongoServer.Create();
MongoDatabase test = server.GetDatabase("Test");

MongoCollection<BsonDocument> users = test.GetCollection("Users");
BsonDocument user = new BsonDocument();
user.Add("FirstName", "John");
user.Add("LastName", "Michael");
user.Add("Address", "123 Main Street");
user.Add("City", "Newport Beach");
user.Add("State", "CA");
user.Add("ZipCode", "92660");
user.Add("Email", "John.Michael@myemail.com");
user.Add("CreatedDate", DateTime.Now);
user.Add("IPAddress", "10.1.1.1");

user = users.Save(user);

string idSTring = user["_id"].ToString().Replace("\"", "");
i3arnon
  • 113,022
  • 33
  • 324
  • 344
atbebtg
  • 4,023
  • 9
  • 37
  • 49
  • creation of ObjectIds are done on the client, not the server, so this should totally be possible. Don't know enough about the c# driver to help you though, sorry :( – Matt Briggs Nov 11 '10 at 13:32

2 Answers2

8

I made some tests with the official driver and found that method MongoCollection.Save returns null; So do not assign result to your constructed user:

//user = users.Save(user);
users.Save(user);

string idStr = user["_id"].ToString();

Console.WriteLine("_id == {0}", idStr);

About drivers check this and this

Community
  • 1
  • 1
Edward83
  • 6,664
  • 14
  • 74
  • 102
  • 1
    I was messing around some more with the code last night and was actually able to come up with the same conclusion. Thanks! – atbebtg Nov 11 '10 at 17:35
3

Use this C# driver and your code will be like this:

        var refMongo = new Mongo();

        refMongo.Connect();

        var test = refMongo.GetDatabase("Test");

        var users = test.GetCollection("Users");

        var user = new MongoDB.Document();

        user.Add("FirstName", "John");
        user.Add("LastName", "Michael");
        user.Add("Address", "123 Main Street");
        user.Add("City", "Newport Beach");
        user.Add("State", "CA");
        user.Add("ZipCode", "92660");
        user.Add("Email", "John.Michael@myemail.com");
        user.Add("CreatedDate", DateTime.Now);
        user.Add("IPAddress", "10.1.1.1");

        users.Save(user);

        string idSTring = user["_id"].ToString();

        Console.WriteLine(idSTring);

I got _id == 4cd9e240df53ca112c000001

Good luck!;)

Edward83
  • 6,664
  • 14
  • 74
  • 102