1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768 |
- using MongoDB.Bson;
- using System;
- using System.Collections.Generic;
- using System.Text;
- namespace CZFW.MDB.Util
- {
- public static class BsonExtensions
- {
- public static string CZToJson(this BsonDocument doc)
- {
- if (doc is null) return null;
- return doc.ConvertToJsonId().ToJson();
- }
- public static string CZToJson(this BsonArray array)
- {
- var res = array.ConvertToJsonId().ToJson();
- return res;
- }
- public static BsonValue GetFieldValue(this BsonDocument doc, string field)
- {
- if (!doc.Contains(field))
- return null;
- var res = doc.GetValue(field);
- return res;
- }
- public static BsonArray ConvertToJsonId(this BsonArray array)
- {
- array.ForEach(x =>
- {
- x = x.AsBsonDocument.ConvertToJsonId();
- //x.AsBsonDocument.Set(0, x.AsBsonDocument.GetValue(0).ToString());
- });
- return array;
- }
- public static BsonDocument ConvertToJsonId(this BsonDocument doc)
- {
- if (doc is null) return null;
- if (doc.TryGetValue(Constants.THE_ID_FILED, out BsonValue value))
- {
- doc.Set(Constants.THE_ID_FILED, value.ToString());
- }
- return doc;
- }
- public static BsonDocument CZBsonParse(this string Json)
- {
- var bson = BsonDocument.Parse(Json);
- return bson.ConvertToBsonId();
- }
- public static BsonDocument ConvertToBsonId(this BsonDocument bson)
- {
- if (!bson.Contains(Constants.THE_ID_FILED))
- return bson;
- if (bson[Constants.THE_ID_FILED].BsonType == BsonType.ObjectId)
- return bson;
- var strId = bson[Constants.THE_ID_FILED].ToString();
- bson[Constants.THE_ID_FILED] = new ObjectId(strId);
- return bson;
- }
- }
- }
|