Guest User

Untitled

a guest
Aug 22nd, 2018
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.54 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. using MongoDB.Bson;
  7. using MongoDB.Bson.IO;
  8. using MongoDB.Driver;
  9. using MongoDB.Driver.Builders;
  10.  
  11. namespace TestUpdateDivisionName {
  12. public interface ICompany {
  13. int Id { get; set; }
  14. string Name { get; set; }
  15. List<IDivision> Divisions { get; set; }
  16. }
  17.  
  18. public interface IDivision {
  19. int Id { get; set; }
  20. string Name { get; set; }
  21. string Location { get; set; }
  22. }
  23.  
  24. public class Company : ICompany {
  25. public int Id { get; set; }
  26. public string Name { get; set; }
  27. public List<IDivision> Divisions { get; set; }
  28. }
  29.  
  30. public class Division : IDivision {
  31. public int Id { get; set; }
  32. public string Name { get; set; }
  33. public string Location { get; set; }
  34. }
  35.  
  36. public static class Program {
  37. public static void Main(string[] args) {
  38. var server = MongoServer.Create("mongodb://localhost/?safe=true");
  39. var database = server["test"];
  40. var companies = database.GetCollection<Company>("Company");
  41.  
  42. companies.RemoveAll();
  43. var company1 = new Company {
  44. Id = 1,
  45. Name = "Test Company",
  46. Divisions = new List<IDivision>() {
  47. new Division { Id = 1, Name = "Test Division 1", Location = "Location 1" },
  48. new Division { Id = 2, Name = "Test Division 2", Location = "Location 2" }
  49. }
  50. };
  51. companies.Insert<ICompany>(company1);
  52.  
  53. var jsonSettings = new BsonJsonWriterSettings { Indent = true };
  54. Console.WriteLine("Before update");
  55. foreach (var company in companies.FindAll()) {
  56. Console.WriteLine(company.ToJson(jsonSettings));
  57. }
  58. Console.WriteLine();
  59.  
  60. var division1 = new Division {
  61. Id = 1,
  62. Name = "New Name",
  63. Location = "New Location"
  64. };
  65.  
  66. companies.Update(
  67. Query.EQ("Divisions._id", 1),
  68. Update.Set("Divisions.$", division1.ToBsonDocument<IDivision>())
  69. );
  70.  
  71. Console.WriteLine("After update");
  72. foreach (var company in companies.FindAll()) {
  73. Console.WriteLine(company.ToJson(jsonSettings));
  74. }
  75.  
  76. Console.WriteLine("Press Enter to continue");
  77. Console.ReadLine();
  78. }
  79. }
  80. }
Add Comment
Please, Sign In to add comment