How do I get the _id of the rcently inserted document after an insert using mongo csharp?

為{幸葍}努か 提交于 2019-12-14 04:17:38

问题


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("\"", "");

回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/4139887/how-do-i-get-the-id-of-the-rcently-inserted-document-after-an-insert-using-mong

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!