Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using MongoDB.Bson;
- using MongoDB.Bson.IO;
- using MongoDB.Driver;
- using MongoDB.Driver.Builders;
- namespace TestUpdateDivisionName {
- public interface ICompany {
- int Id { get; set; }
- string Name { get; set; }
- List<IDivision> Divisions { get; set; }
- }
- public interface IDivision {
- int Id { get; set; }
- string Name { get; set; }
- string Location { get; set; }
- }
- public class Company : ICompany {
- public int Id { get; set; }
- public string Name { get; set; }
- public List<IDivision> Divisions { get; set; }
- }
- public class Division : IDivision {
- public int Id { get; set; }
- public string Name { get; set; }
- public string Location { get; set; }
- }
- public static class Program {
- public static void Main(string[] args) {
- var server = MongoServer.Create("mongodb://localhost/?safe=true");
- var database = server["test"];
- var companies = database.GetCollection<Company>("Company");
- companies.RemoveAll();
- var company1 = new Company {
- Id = 1,
- Name = "Test Company",
- Divisions = new List<IDivision>() {
- new Division { Id = 1, Name = "Test Division 1", Location = "Location 1" },
- new Division { Id = 2, Name = "Test Division 2", Location = "Location 2" }
- }
- };
- companies.Insert<ICompany>(company1);
- var jsonSettings = new BsonJsonWriterSettings { Indent = true };
- Console.WriteLine("Before update");
- foreach (var company in companies.FindAll()) {
- Console.WriteLine(company.ToJson(jsonSettings));
- }
- Console.WriteLine();
- var division1 = new Division {
- Id = 1,
- Name = "New Name",
- Location = "New Location"
- };
- companies.Update(
- Query.EQ("Divisions._id", 1),
- Update.Set("Divisions.$", division1.ToBsonDocument<IDivision>())
- );
- Console.WriteLine("After update");
- foreach (var company in companies.FindAll()) {
- Console.WriteLine(company.ToJson(jsonSettings));
- }
- Console.WriteLine("Press Enter to continue");
- Console.ReadLine();
- }
- }
- }
Add Comment
Please, Sign In to add comment