var client = new MongoClient(MongoAddress); var collection = client.GetDatabase(HelloDatabase).GetCollection<UserEntity>(UserCollection);
Create
剛開始肯定沒有資料的,所以我們會先建立幾筆資料做為測試
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
//建立一筆資料 privatestaticasyncvoidCreateUser() { await GetUsersCollection().InsertOneAsync( new UserEntity{ Name = "Shaka", Country = "Unknown", City = "Zodiac Temple"} ); } //一次建立多筆資料 privatestaticasyncvoidCreateMultiUsers() { await GetUsersCollection().InsertManyAsync(new List<UserEntity> { new UserEntity{ Name = "Jack", Country = "Taiwan", City = "Taipei"}, new UserEntity{ Name = "Sion", Country = "Unknown", City = "Underworld"}, new UserEntity{ Name = "Saga", Country = "Unknown", City = "Zodiac Temple"} } ); }
Read
1 2 3 4 5 6 7 8 9 10 11 12
privatestaticasync Task<List<UserEntity>> GetAllUsers() { var result = await GetUsersCollection().FindAsync(FilterDefinition<UserEntity>.Empty).Result.ToListAsync(); return result; } //尋找 name 欄位等於參數的 privatestaticasync Task<List<UserEntity>> GetUser(string name) { var filter = Builders<UserEntity>.Filter.Eq("name", name); var result = await GetUsersCollection().FindAsync(filter).Result.ToListAsync(); return result; }
Update
這個範例是尋找名稱為 name 的使用者,將他的 city 欄位改為 newCity
1 2 3 4 5 6 7
privatestaticasync Task<bool> UpdateCity(string name, string newCity) { var filter = Builders<UserEntity>.Filter.Eq("name", name); var update = Builders<UserEntity>.Update.Set("city", newCity); var result = await GetUsersCollection().UpdateOneAsync(filter, update); return result.IsAcknowledged; }
Delete
1 2 3 4 5 6 7 8 9 10 11
privatestaticasync Task<bool> DeleteAll() { var result = await GetUsersCollection().DeleteManyAsync(FilterDefinition<UserEntity>.Empty); return result.IsAcknowledged; } privatestaticasync Task<bool> DeleteOne(string name) { var filter = Builders<UserEntity>.Filter.Eq("name", name); var result = await GetUsersCollection().DeleteOneAsync(filter); return result.IsAcknowledged; }