1. 我正在使用c#console应用程序中的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()
    

我的代码怎么了?

推荐答案

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

Mongodb相关问答推荐

MongoDB—基于数组中同一文档中的另一个字段更新字段

数组过滤器 MongoDB

MongoDB 按日期时间字段查询 1h 间隔

尽管前一阶段输出文档,$group stage 仍返回零文档

如何为具有相同名称的嵌套字段创建文本索引

如何在 MongoDB 中已经存在的 slug 中添加一个随机数?

对 MongoDB 集合中的对象数组进行排序

映射数组导致 mongodb 聚合

将 MongoDB BsonDocument 转换为字符串

MongoDB 更改流副本集限制

Mongo 可尾游标与 Redis 发布/订阅

Mongodb:查询嵌套在数组中的json对象

如何在我的Meteor 应用程序数据库中使用 mongoimport?

带有排序功能的mongoose findOne

如何获取 Mongoid 文档的所有字段名称?

MongoError:Topology is closed, please connect despite established database connection

MongoDB聚合将字符串数组连接到单个字符串

如何从 Mongoose 模型对象中获取集合名称

单个语句中的多个 mongo 更新运算符?

MongoDB Compass timeouts超时