Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

  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?

like image 902
Chandan Avatar asked Mar 29 '15 10:03

Chandan


People also ask

How manually insert data in MongoDB?

The insert() Method To insert data into MongoDB collection, you need to use MongoDB's insert() or save() method.

What is insert command in MongoDB?

The insert command inserts one or more documents and returns a document containing the status of all inserts. The insert methods provided by the MongoDB drivers use this command internally.

Which command is used to insert document in MongoDB?

insertOne() inserts a single document into a collection. The following example inserts a new document into the inventory collection.


1 Answers

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" });
}
like image 83
Chandan Avatar answered Oct 11 '22 05:10

Chandan