如何使用mongodb在c#.net应用程序中插入,更新,删除

时间:2017-05-27 12:49:12

标签: c# mongodb mongodb-query

我想知道如何使用新的api使用mongodb插入,删除,更新和搜索。 这是我的插入查询。我想用这个新的API编写更新和删除。

//插入查询

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!");
            }

1 个答案:

答案 0 :(得分:0)

我同意Csharp驱动程序文档并不总是清晰或最新...

这是我的实施:

 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);
    }
}