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

Cha*_*dan 15 .net c# mongodb mongodb-.net-driver

  1. 我正在使用MongoClient我的c#console应用程序连接到MongoDB

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

  1. 我的代码

      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; }
    }
    
    Run Code Online (Sandbox Code Playgroud)
  2. 成功运行上面的代码后,我无法使用此命令在MongoDB数据库中找到此记录:

    db.entities.find().pretty()
    
    Run Code Online (Sandbox Code Playgroud)

我的代码出了什么问题?

Cha*_*dan 18

这是我创建的用于将数据插入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" });
}
Run Code Online (Sandbox Code Playgroud)

  • 如果你知道为什么这个代码有效,以及为什么另一个代码失败了,那么在你的答案中包含这些信息会很有帮助.知道**为什么**某些东西是否有效(即使原因是"API中的错误")可以帮助读者提高远远超出这个狭窄范例的帮助. (9认同)
  • 看起来像集合中的 async 方法和 await 关键字。InsertOneAsyc 做了上面帖子中@Inba 提到的技巧 (2认同)

Inb*_*ba 7

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

Console.ReadKey()或collection.InsertOneAsync(entiry).Wait()或任何其他形式的停止退出几分之一秒都可以解决问题.


小智 5

对于.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();
Run Code Online (Sandbox Code Playgroud)

来自inmongodb的参考

  • MongoDB已经是命名空间了,我假设这段代码不会编译? (2认同)