-1

i want to know about how to insert, delete, update and search using mongodb with new api. this is my insert query. i want to write update and delete with this new api.

//insert query

string connectionString = "mongodb://127.0.0.1:27017";
            MongoClient client0 = new MongoClient(connectionString);
            IMongoDatabase mydatabase = client0.GetDatabase("mydb");
            IMongoCollection<user_data> mycollection = mydatabase.GetCollection<user_data>("testcollection");
            mycollection.InsertOne(new user_data { first_name = txtFirstName.Text, last_name = txtLastName.Text, age = txtAge.Text, location = txtLocation.Text });
            {
                MessageBox.Show("Saved Successfully!");
            }
K.Mihiranga
  • 147
  • 1
  • 2
  • 13
  • [Removing items](https://stackoverflow.com/questions/8867032/how-to-remove-one-document-by-id-using-the-official-c-sharp-driver-for-mongo) , [Updating items](https://stackoverflow.com/questions/30257013/mongodb-c-sharp-driver-2-0-update-document) Please use the search function. – Skami Jun 21 '17 at 10:34

1 Answers1

0

I agree that the Csharp driver documentation isn't always clear or up to date...

Here is my implementation :

 public class MongoRepository
{
    const string DB_NAME = "dbname";
    public const string HOST = "serveradress";
    const string CONNECT_STRING = "connectionstring";
    private IMongoClient _client;
    private IMongoDatabase _db {

        get { return this._client.GetDatabase(DB_NAME); }
    }
    public MongoRepository()
    {
        _client = new MongoClient(CONNECT_STRING);
    }
    //Add a BSON document from a json string
    public void Add(string json, string collectionName)
    {
        var document = BsonSerializer.Deserialize<BsonDocument>(json);
        var collection = _db.GetCollection<BsonDocument>(collectionName);
        collection.InsertOne(document);
    }

    //Add an item of the given type 
    public void Add<T>(T item) where T : class, new()
    {
        _db.GetCollection<T>(typeof(T).Name).InsertOne(item);

    }
    public async Task UpdateDocument<T>(ObjectId Id, T item )
    {
        var startTime = DateTime.UtcNow;
        try
        {
            var bsonWriter = new BsonDocumentWriter(new BsonDocument(), BsonDocumentWriterSettings.Defaults);
            BsonSerializer.Serialize<GlobalModel_Root>(bsonWriter, GlobalModel.rootGM);
            var doc = bsonWriter.Document;
            var collection = _db.GetCollection<BsonDocument>(typeof(T).Name);
            var filter = Builders<BsonDocument>.Filter.Eq("_id", Id);
            var entity = collection.Find(filter).FirstOrDefault();
            using (var timeoutCancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(60)))
            {
                await collection.ReplaceOneAsync(filter, doc, null, timeoutCancellationTokenSource.Token);
            }
        }
        catch (OperationCanceledException ex)
        {
            var endTime = DateTime.UtcNow;
            var elapsed = endTime - startTime;
            Console.WriteLine("Operation was cancelled after {0} seconds.", elapsed.TotalSeconds);
        }   
    }
    public void Delete<T>(T item) where T : class, new()
    {
        //WorkAround for DeleteOne parameter
        ObjectFilterDefinition<T> filter = new ObjectFilterDefinition<T>(item);
        // Remove the object.
        _db.GetCollection<T>(typeof(T).Name).FindOneAndDelete(filter);
    }
}
aurelienjo
  • 55
  • 1
  • 9