【问题标题】:How to insert data into a mongodb collection using the c# 2.0 driver?如何使用 c# 2.0 驱动程序将数据插入到 mongodb 集合中?
【发布时间】:2015-03-29 10:08:35
【问题描述】:
  1. 我在我的 c# 控制台应用程序中使用 MongoClient 连接到 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; }
    }
    
  2. 成功运行上面的代码后,我无法使用这个命令在MongoDB数据库中找到这条记录:

    db.entities.find().pretty()
    

我的代码有什么问题?

【问题讨论】:

    标签: c# .net mongodb mongodb-.net-driver


    【解决方案1】:

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

    【讨论】:

    • 如果您知道此代码为何有效,以及另一个代码为何失败,那么在您的答案中包含此类信息会很有帮助。了解为什么某项工作或不工作(即使原因是“API 中的错误”)可以帮助读者进行改进,而不仅仅是在这一个狭窄的例子中帮助他。
    • 在控制台应用程序中,我猜它在创建商店之前就退出了应用程序。我添加了异步方法,然后在主要静态方法中添加了 readline,它开始工作。静态无效主要(字符串[] args){DoSomethingAsync(); Console.ReadLine(); }
    • 在集合中看起来像 async 方法和 await 关键字。InsertOneAsyc 完成了上面帖子中@Inba 提到的技巧
    • async/await 会等待,实际上如果出现超时错误,catch 块就会被命中。我不确定这是因为添加了异步/等待而“工作”的原因
    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

      • MongoDB 已经是一个命名空间,我认为这段代码不会编译?
      • 你是对的,它是一个命名空间,但是你可能已经在 using 语句中定义了它,所以这段代码可以正常工作。使用它作为局部变量名没有问题。虽然我个人会避免这种情况,但更多的是因为我自己的困惑。
      猜你喜欢
      • 1970-01-01
      • 2019-11-12
      • 1970-01-01
      • 2013-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-16
      相关资源
      最近更新 更多