BsonExtensions.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. using MongoDB.Bson;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Text;
  5. namespace CZFW.MDB.Util
  6. {
  7. public static class BsonExtensions
  8. {
  9. public static string CZToJson(this BsonDocument doc)
  10. {
  11. if (doc is null) return null;
  12. return doc.ConvertToJsonId().ToJson();
  13. }
  14. public static string CZToJson(this BsonArray array)
  15. {
  16. var res = array.ConvertToJsonId().ToJson();
  17. return res;
  18. }
  19. public static BsonValue GetFieldValue(this BsonDocument doc, string field)
  20. {
  21. if (!doc.Contains(field))
  22. return null;
  23. var res = doc.GetValue(field);
  24. return res;
  25. }
  26. public static BsonArray ConvertToJsonId(this BsonArray array)
  27. {
  28. array.ForEach(x =>
  29. {
  30. x = x.AsBsonDocument.ConvertToJsonId();
  31. //x.AsBsonDocument.Set(0, x.AsBsonDocument.GetValue(0).ToString());
  32. });
  33. return array;
  34. }
  35. public static BsonDocument ConvertToJsonId(this BsonDocument doc)
  36. {
  37. if (doc is null) return null;
  38. if (doc.TryGetValue(Constants.THE_ID_FILED, out BsonValue value))
  39. {
  40. doc.Set(Constants.THE_ID_FILED, value.ToString());
  41. }
  42. return doc;
  43. }
  44. public static BsonDocument CZBsonParse(this string Json)
  45. {
  46. var bson = BsonDocument.Parse(Json);
  47. return bson.ConvertToBsonId();
  48. }
  49. public static BsonDocument ConvertToBsonId(this BsonDocument bson)
  50. {
  51. if (!bson.Contains(Constants.THE_ID_FILED))
  52. return bson;
  53. if (bson[Constants.THE_ID_FILED].BsonType == BsonType.ObjectId)
  54. return bson;
  55. var strId = bson[Constants.THE_ID_FILED].ToString();
  56. bson[Constants.THE_ID_FILED] = new ObjectId(strId);
  57. return bson;
  58. }
  59. }
  60. }