How to insert data into a mongodb collection using the c# 2.0 driver?

一曲冷凌霜 提交于 2019-11-27 17:35:39

问题


  1. I'm using the MongoClient in my c# console application to connect to MongoDB

https://github.com/mongodb/mongo-csharp-driver/releases/tag/v2.0.0-rc0

  1. My code

      class Program
       {
           static void Main(string[] args)
           {
            const string connectionString = "mongodb://localhost:27017";
    
            // Create a MongoClient object by using the connection string
            var client = new MongoClient(connectionString);
    
            //Use the MongoClient to access the server
            var database = client.GetDatabase("test");
    
            var collection = database.GetCollection<Entity>("entities");
    
            var entity = new Entity { Name = "Tom" };
            collection.InsertOneAsync(entity);
            var id = entity._id;          
        }
    }
    
    public class Entity
    {
        public ObjectId _id { get; set; }
        public string Name { get; set; }
    }
    
  2. After successfully running the code above, I'm unable to find this record in the MongoDB database using this command:

    db.entities.find().pretty()
    

What's wrong with my code?


回答1:


This is the method I created for inserting data into MongoDB, which is working fine now.

static async void DoSomethingAsync()
{
    const string connectionString = "mongodb://localhost:27017";

    // Create a MongoClient object by using the connection string
    var client = new MongoClient(connectionString);

    //Use the MongoClient to access the server
    var database = client.GetDatabase("test");

    //get mongodb collection
    var collection = database.GetCollection<Entity>("entities");
    await collection.InsertOneAsync(new Entity { Name = "Jack" });
}



回答2:


The reason is you need to wait to get the store to create the document. In this case collection.InsertOneAsync(entity); the execution exit before creating the document.

Either Console.ReadKey() or collection.InsertOneAsync(entiry).Wait() or any other form of stopping exit for a fraction of second will do the trick.




回答3:


for .net 4.5 and greater versions and mongodriver 2x series follow the below code

var Client = new MongoClient();
var MongoDB = Client.GetDatabase("shop");
var Collec = MongoDB.GetCollection<BsonDocument>("computers");
var documnt = new BsonDocument
{
    {"Brand","Dell"},
    {"Price","400"},
    {"Ram","8GB"},
    {"HardDisk","1TB"},
    {"Screen","16inch"}
};
Collec.InsertOneAsync(documnt);
Console.ReadLine();


来源:https://stackoverflow.com/questions/29327856/how-to-insert-data-into-a-mongodb-collection-using-the-c-sharp-2-0-driver

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