如何使用c#2.0驱动程序将数据插入mongodb集合?

时间:2022-04-04 07:17:16
  1. I'm using the MongoClient in my c# console application to connect to MongoDB
  2. 我在我的c#控制台应用程序中使用MongoClient连接到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. 我的代码类程序    {        static void Main(string [] args)        {         const string connectionString =“mongodb:// localhost:27017”;         //使用连接字符串创建MongoClient对象         var client = new MongoClient(connectionString);         //使用MongoClient访问服务器         var database = client.GetDatabase(“test”);         var collection = database.GetCollection (“entities”);         var entity = new Entity {Name =“Tom”};         collection.InsertOneAsync(实体);         var id = entity._id;     } } 公共类实体 {     public ObjectId _id {get;组; }     public string Name {get;组; } }

  3. After successfully running the code above, I'm unable to find this record in the MongoDB database using this command:

    成功运行上面的代码后,我无法使用此命令在MongoDB数据库中找到此记录:

    db.entities.find().pretty()
    

What's wrong with my code?

我的代码出了什么问题?

3 个解决方案

#1


16  

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

这是我创建的用于将数据插入MongoDB的方法,现在工作正常。

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


5  

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.

原因是您需要等待商店创建文档。在这种情况下collection.InsertOneAsync(entity);创建文档之前的执行退出。

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

Console.ReadKey()或collection.InsertOneAsync(entiry).Wait()或任何其他形式的停止退出一小段时间都可以解决问题。

#3


4  

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

对于.net 4.5及更高版本和mongodriver 2x系列,请遵循以下代码

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

Reference from inmongodb

来自inmongodb的参考

#1


16  

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

这是我创建的用于将数据插入MongoDB的方法,现在工作正常。

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


5  

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.

原因是您需要等待商店创建文档。在这种情况下collection.InsertOneAsync(entity);创建文档之前的执行退出。

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

Console.ReadKey()或collection.InsertOneAsync(entiry).Wait()或任何其他形式的停止退出一小段时间都可以解决问题。

#3


4  

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

对于.net 4.5及更高版本和mongodriver 2x系列,请遵循以下代码

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

Reference from inmongodb

来自inmongodb的参考