public static object ToObject(BsonValue value) //_120509_173140 keep consistent { if (value == null) { return(null); } switch (value.BsonType) { case BsonType.Array: return(new Collection((BsonArray)value)); // wrapper case BsonType.Binary: return(BsonTypeMapper.MapToDotNetValue(value) ?? value); // byte[] or Guid else self case BsonType.Boolean: return(((BsonBoolean)value).Value); case BsonType.DateTime: return(((BsonDateTime)value).ToUniversalTime()); case BsonType.Document: return(new Dictionary((BsonDocument)value)); // wrapper case BsonType.Double: return(((BsonDouble)value).Value); case BsonType.Int32: return(((BsonInt32)value).Value); case BsonType.Int64: return(((BsonInt64)value).Value); case BsonType.Null: return(null); case BsonType.ObjectId: return(((BsonObjectId)value).Value); case BsonType.String: return(((BsonString)value).Value); default: return(value); } }
public string Get(string id) { var doc = FindOne(id); var result = Newtonsoft.Json.JsonConvert.SerializeObject(BsonTypeMapper.MapToDotNetValue(doc)); return(result); }
/// <summary> /// Find record /// </summary> /// <param name="entityName"></param> /// <param name="id"></param> /// <returns></returns> public IEnumerable <KeyValuePair <string, object> > Find(string entityName, Guid id) { var mongoCollection = MongoStaticContext.Context.GetBsonCollection(RECORD_COLLECTION_PREFIX + entityName); var doc = mongoCollection.FindOne(Query.EQ("_id", id)); if (doc == null) { return(null); } List <KeyValuePair <string, object> > record = new List <KeyValuePair <string, object> >(); foreach (var fieldName in doc.Names) { if (fieldName == "_id") { record.Add(new KeyValuePair <string, object>("id", BsonTypeMapper.MapToDotNetValue(doc["_id"]))); } else { record.Add(new KeyValuePair <string, object>(fieldName, ConvertBsonValueToObject(doc[fieldName]))); } } return(record); }
/// <summary> /// Deletes record /// </summary> /// <param name="entityName"></param> /// <param name="id"></param> /// <returns></returns> public IEnumerable <KeyValuePair <string, object> > Delete(string entityName, Guid id) { var mongoCollection = MongoStaticContext.Context.GetBsonCollection(RECORD_COLLECTION_PREFIX + entityName); var doc = mongoCollection.FindOne(Query.EQ("_id", id)); if (doc == null) { throw new StorageException("There is no document with such id to update."); } mongoCollection.Remove(Query.EQ("_id", id)); List <KeyValuePair <string, object> > record = new List <KeyValuePair <string, object> >(); foreach (var fieldName in doc.Names) { if (fieldName == "_id") { record.Add(new KeyValuePair <string, object>("id", BsonTypeMapper.MapToDotNetValue(doc["_id"]))); } else { record.Add(new KeyValuePair <string, object>(fieldName, ConvertBsonValueToObject(doc[fieldName]))); } } return(record); }
/// <summary> /// Create a dynamic collection of Bson documents. /// </summary> /// <param name="documents">The collection of Bson documents.</param> /// <param name="collectionName">The name of the collection.</param> /// <returns>The collection of dynamic models.</returns> public virtual object[] CreateDynamicModel(IEnumerable <BsonDocument> documents, string collectionName = "MongoDBCollection") { List <object> result = new List <object>(); // Make sure documents exits. if (documents != null && documents.Count() > 0) { // Create the dynamic type builder. Nequeo.Reflection.DynamicTypeBuilder builder = new Reflection.DynamicTypeBuilder("DynamicBsonDocumentModule"); // For each document. foreach (BsonDocument item in documents) { int i = 0; // Get the current row. Dictionary <string, object> row = item.ToDictionary(); // Get all document property names. List <string> propertyName = new List <string>(); foreach (KeyValuePair <string, object> id in row) { // Get the name. string name = id.Key; if (name.ToLower().Contains("_id")) { name = "Id"; } // Add the name. propertyName.Add(name); } // Create the dynamic type. Nequeo.Reflection.DynamicPropertyValue[] dynamicTypeProperties = new Nequeo.Reflection.DynamicPropertyValue[row.Count()]; // Get the document values. IEnumerable <BsonValue> values = item.Values; // For each Bson value. foreach (BsonValue bsonValue in values) { // Map the Bson type tp .Net type. object netValue = BsonTypeMapper.MapToDotNetValue(bsonValue); Nequeo.Reflection.DynamicPropertyValue propertyValue = new Reflection.DynamicPropertyValue(propertyName[i], netValue.GetType(), netValue); // Add the value to the list of dynamic types. dynamicTypeProperties[i] = propertyValue; i++; } // Create the model from the document. object model = builder.Create(collectionName, dynamicTypeProperties); result.Add(model); } } // Return the dynamic array. return(result.ToArray()); }
public void Handle(CommandStartedEvent startedEvent) { var commandName = startedEvent.CommandName; if (commandName != "insert") { return; } var tracer = GlobalTracer.Instance; var scope = tracer.BuildSpan(commandName).StartActive(finishSpanOnDispose: true); var documents = startedEvent.Command.GetValue("documents").AsBsonArray; var ids = documents.Select(doc => doc.AsBsonDocument.GetValue("_id").ToString()); scope.Span.SetTag("event.id", $"mongo-{Guid.NewGuid()}"); scope.Span.SetTag("resource.name", startedEvent.DatabaseNamespace.DatabaseName); scope.Span.SetTag("resource.type", "mongodb"); scope.Span.SetTag("resource.operation", commandName); scope.Span.SetTag("mongodb.db_url", GetEndpointUrl(startedEvent.ConnectionId.ServerId.EndPoint)); scope.Span.SetTag("mongodb.db_name", startedEvent.DatabaseNamespace.DatabaseName); scope.Span.SetTag("mongodb.collection_name", startedEvent.Command.GetValue("insert").AsString); scope.Span.SetTag("mongodb.inserted_ids", Utils.SerializeObject(ids)); scope.Span.SetDataIfNeeded("mongodb.items", BsonTypeMapper.MapToDotNetValue(documents)); // store the scope to finish when the command is finished this.scopes.Add(startedEvent.RequestId, scope); Utils.DebugLogIfEnabled("MongoDb event"); }
private TClass Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args) { CheckItemMap(); var bsonReader = context.Reader; if (bsonReader.GetCurrentBsonType() == BsonType.Null) { bsonReader.ReadNull(); return(null); } else { var idref = dbRef.Deserialize(context, args); if (idref == null || idref.Id == null) { return(null); } TClass obj = ReflectionTools.CreateInstance <TClass>(); itemIdMap.Setter.Invoke(obj, BsonTypeMapper.MapToDotNetValue(idref.Id)); //TODO: Buscar na collection correta a instancia completa. return(obj); } }
private bool OutOfFilter(Filter query, BsonDocument nestedDoc) { if (query == null) { return(false); } string tagName = query.TagName; if (query.TagName == "key") { tagName = "_id"; } if (!nestedDoc.Names.Contains(tagName)) { return(true); } IComparable docValue = (IComparable)BsonTypeMapper.MapToDotNetValue(nestedDoc[tagName]); if (query.Value != null && docValue.CompareTo((IComparable)query.Value) != 0) { return(true); } if (query.Start != null && docValue.CompareTo((IComparable)query.Start) < 0) { return(true); } if (query.End != null && docValue.CompareTo((IComparable)query.End) > 0) { return(true); } return(false); }
public static Snapshot ToSnapshot(this BsonDocument doc, IDocumentSerializer serializer) { if (doc == null) { return(null); } BsonDocument id = doc[MongoFields.Id].AsBsonDocument; string bucketId = id[MongoFields.BucketId].AsString; string streamId = id[MongoFields.StreamId].AsString; int streamRevision = id[MongoFields.StreamRevision].AsInt32; BsonValue bsonPayload = doc[MongoFields.Payload]; object payload; switch (bsonPayload.BsonType) { case BsonType.Binary: payload = serializer.Deserialize <object>(bsonPayload.AsByteArray); break; case BsonType.Document: payload = BsonSerializer.Deserialize <object>(bsonPayload.AsBsonDocument); break; default: payload = BsonTypeMapper.MapToDotNetValue(bsonPayload); break; } return(new Snapshot(bucketId, streamId, streamRevision, payload)); }
/// <summary> /// /// </summary> /// <param name="jsonObject"></param> /// <returns></returns> private IEnumerable <FilterDefinition <BsonDocument> > CreateFilterByObject(String jsonObject) { List <FilterDefinition <BsonDocument> > result = new List <FilterDefinition <BsonDocument> >(); BsonDocument filter_doc = BsonDocument.Parse(jsonObject); foreach (var element in filter_doc.Elements) { var value = BsonTypeMapper.MapToDotNetValue(element.Value); if (value != null) { if (value is String) { // String String str_value = value as String; if (false == String.IsNullOrWhiteSpace(str_value)) { // Ищем подстроку result.Add(Builders <BsonDocument> .Filter.Regex(element.Name, str_value)); Debug.WriteLine(String.Format("NAme: {0} Value:{1}", element.Name, str_value)); } } else { // другие типы - точное соответствие result.Add(Builders <BsonDocument> .Filter.Eq(element.Name, value)); Debug.WriteLine(String.Format("NAme: {0} Value:{1}", element.Name, value)); } } } if (0 == result.Count) { } return(result); }
public static IDictionary <string, object> BsonDocumentToDictionary(BsonDocument document) { var result = new Dictionary <string, object>(); foreach (var element in document.Elements) { if (element.Value.IsBsonArray) { var list = new List <IDictionary <string, object> >(); foreach (var d in element.Value.AsBsonArray) { list.Add(BsonDocumentToDictionary(d.AsBsonDocument)); } result.Add(element.Name, list); } else if (element.Value.IsBsonDocument) { result.Add(element.Name, BsonDocumentToDictionary(element.Value.AsBsonDocument)); } else { result.Add(element.Name, BsonTypeMapper.MapToDotNetValue(element.Value)); } } return(result); }
public virtual async Task <DynamicObject> CreateAsync(DynamicObject model) { var bsonDocument = BsonDocument.Create(model.ToDynamic()); var insertedDocument = await this._repository.InsertAsync(bsonDocument) as BsonDocument; return(DynamicObject.Create(BsonTypeMapper.MapToDotNetValue(insertedDocument) as Dictionary <string, object>)); }
private Node BuildNode(BsonValue token, Unit unit) { if (unit.Leaf) { if (token.IsValidDateTime) { return(new Node(unit.Key, ((DateTime)BsonTypeMapper.MapToDotNetValue(token)).ToLocalTime())); } return(new Node(unit.Key, BsonTypeMapper.MapToDotNetValue(token))); } else { Node node = new Node(unit.Key); if (token.IsBsonArray) { foreach (var row in token.AsBsonArray) { BuildRow(row as BsonValue, unit, node); } } else if (!token.IsBsonNull) { BuildRow(token, unit, node); } return(node); } }
private void RegisterArrayProperty(MongoContext context, ResourceType collectionType, BsonElement element) { var propertyName = GetResourcePropertyName(element, ResourceTypeKind.EntityType); var bsonArray = element.Value.AsBsonArray; if (bsonArray != null) { foreach (var arrayValue in bsonArray) { if (arrayValue.AsBsonValue == BsonNull.Value) { continue; } if (arrayValue.BsonType == BsonType.Document) { RegisterDocumentProperties(context, collectionType, new BsonElement(element.Name, arrayValue)); } else if (ResolveResourceProperty(collectionType, propertyName) == null) { // OData protocol doesn't support collections of collections if (arrayValue.BsonType != BsonType.Array) { var mappedType = BsonTypeMapper.MapToDotNetValue(arrayValue).GetType(); this.instanceMetadataCache.AddCollectionProperty(collectionType, propertyName, mappedType); } } } } }
/// <summary> /// Gets a document from the database with the specified id within the specified collection. /// </summary> /// <param name="id">The id of the document to retrieve.</param> /// <param name="collection">The name of the collection to get the document from.</param> /// <returns>The document with the specified id, or null if there was an error, or the id does not exist.</returns> public dynamic Get(string id, string collection) { if (!string.IsNullOrWhiteSpace(id) && !string.IsNullOrWhiteSpace(collection) && isCollectionNameValid(collection)) { try { MongoCollection mongoCollection = database.GetCollection <BsonDocument>(collection); // Get the document associated with the id in the collection. BsonDocument document = mongoCollection.FindOneByIdAs <BsonDocument>(new ObjectId(id)); // Convert the document into an ExpandoObject with like properties to return. ExpandoObject returnObject = new ExpandoObject(); foreach (string key in document.ToDictionary().Keys) { ((IDictionary <string, object>)returnObject)[key] = BsonTypeMapper.MapToDotNetValue(document[key]); } // Return the object. return(returnObject); } catch (Exception) { // There was an error geting the document. return(null); } } else { // A null or empty id or collection was supplied or the collection name was invalid. return(null); } }
public static Snapshot ToSnapshot(this BsonDocument doc, IDocumentSerializer serializer) { if (doc == null) { return(null); } var id = doc["_id"].AsBsonDocument; var streamId = id["StreamId"].AsGuid; var streamRevision = id["StreamRevision"].AsInt32; var bsonPayload = doc["Payload"]; object payload; switch (bsonPayload.BsonType) { case BsonType.Binary: payload = serializer.Deserialize <object>(bsonPayload.AsByteArray); break; case BsonType.Document: payload = BsonSerializer.Deserialize <object>(bsonPayload.AsBsonDocument); break; default: payload = BsonTypeMapper.MapToDotNetValue(bsonPayload); break; } return(new Snapshot( streamId, streamRevision, payload)); }
public async Task <IList <string> > GetListDevaces(IList <Guid> devaceSerialNumbers) { // var result = await _context.Devices.FindAsync(_ => _.SerialNumber ); //var filter = Builders<BsonDocument>.Filter; //BsonElement bsonElement = new BsonElement("_id", devaceSerialNumbers[0]); //var filterDefinition = filter.In(_ => _.GetValue("_id")., bsonElement); //var cursor = await _deviceCollection.FindAsync(filterDefinition); var devices = new List <string>(); BsonDocument filter = new BsonDocument(); var cursor = await _deviceCollection.FindAsync(filter); await cursor.ForEachAsync(bsonDocument => { Parallel.ForEach(devaceSerialNumbers, item => { var bsonDocumentId = bsonDocument.GetElement("_id").Value.AsGuid; if (bsonDocumentId == item) { string json = JsonConvert.SerializeObject(BsonTypeMapper.MapToDotNetValue(bsonDocument)) .Replace("_", ""); devices.Add(json); } }); }); return(devices); }
private void GetFromDB() { //BSON document to store the data from the GroundFrame.MongoDB BsonDocument Document; using (GFMongoConnector MongoConnector = Globals.GetGFMongoConnector(this._Environment)) { IMongoDatabase db = MongoConnector.MongoClient.GetDatabase("groundframeQueuer"); var collection = db.GetCollection <BsonDocument>("processQueue"); string filter = string.Format(@"{{ key: '{0}'}}", this._Key); Document = collection.Find(filter).FirstOrDefault(); } string JSON = JsonConvert.SerializeObject(BsonTypeMapper.MapToDotNetValue(Document)); QueuerProcess TempQueuerProcess = JsonConvert.DeserializeObject <QueuerProcess>(JSON, new QueuerProcessConverter(this._Environment)); this._Request = TempQueuerProcess.Request; this._Key = TempQueuerProcess.Key; this._AppAPIKey = TempQueuerProcess.AppAPIKey; this._AppUserAPIKey = TempQueuerProcess.AppUserAPIKey; this._Authenticated = TempQueuerProcess.Authenticated; this._ID = TempQueuerProcess.ID; this._ExecuteNow = TempQueuerProcess.ExecuteNow; this._QueueTime = TempQueuerProcess.QueueTime; this._Authenticated = TempQueuerProcess.Authenticated; }
public async Task GFMongoConnector_Constructor_ServerPort() { GroundFrame.Core.GFMongoConnector MongoConnector = new Core.GFMongoConnector("localhost", "27017"); IMongoDatabase db = MongoConnector.MongoClient.GetDatabase("groundframeControl"); IMongoCollection <BsonDocument> collection = db.GetCollection <BsonDocument>("environments"); string TestJSON = @"{ ""environment"": ""localhost"", ""config"":{ ""gfSqlServer"": ""(localdb)\\MSSQLLocalDB"", ""gfDbName"": ""GroundFrame.SQL"" } }"; using IAsyncCursor <BsonDocument> cursor = await collection.FindAsync(new BsonDocument ()); while (await cursor.MoveNextAsync()) { IEnumerable <BsonDocument> batch = cursor.Current; foreach (BsonDocument document in batch) { string Test = JsonConvert.SerializeObject(BsonTypeMapper.MapToDotNetValue(document)); Console.WriteLine(Test); Console.WriteLine(); } } }
public ActionResult PrintSessionValDouble() { var val = Session.Mongo <double>("value"); double dobVal = (double)BsonTypeMapper.MapToDotNetValue(val); ViewBag.sessionVal = dobVal.ToString("G"); return(View("~/Views/Default/PrintSessionVal.cshtml")); }
/// <summary> /// Updates record /// </summary> /// <param name="entityName"></param> /// <param name="recordData"></param> /// <returns></returns> public IEnumerable <KeyValuePair <string, object> > Update(string entityName, IEnumerable <KeyValuePair <string, object> > recordData) { var mongoCollection = MongoStaticContext.Context.GetBsonCollection(RECORD_COLLECTION_PREFIX + entityName); Guid?id = null; foreach (var rec in recordData) { string fieldName = ProcessQueryIDFieldName(rec.Key); if (fieldName == "_id") { id = (Guid)ConvertObjectToBsonValue(rec.Value); } } if (id == null) { throw new StorageException("ID is missing. Cannot update records without ID specified."); } var doc = mongoCollection.FindOne(Query.EQ("_id", id)); if (doc == null) { throw new StorageException("There is no document with such id to update."); } foreach (var rec in recordData) { string fieldName = ProcessQueryIDFieldName(rec.Key); doc[fieldName] = ConvertObjectToBsonValue(rec.Value); } var updateSuccess = mongoCollection.Save(doc).DocumentsAffected > 0; if (!updateSuccess) { throw new StorageException("Failed to update record."); } List <KeyValuePair <string, object> > record = new List <KeyValuePair <string, object> >(); foreach (var fieldName in doc.Names) { if (fieldName == "_id") { record.Add(new KeyValuePair <string, object>("id", BsonTypeMapper.MapToDotNetValue(doc["_id"]))); } else { record.Add(new KeyValuePair <string, object>(fieldName, ConvertBsonValueToObject(doc[fieldName]))); } } return(record); }
private object ConvertBsonValueToObject(BsonValue bsonValue) { var value = BsonTypeMapper.MapToDotNetValue(bsonValue); if (value is long) { return(MongoTypeConvertor.LongToDecimal(value)); } return(value); }
public static Dictionary <Tkey, Tvalue> AsDictionary <Tkey, Tvalue>(this BsonValue bsonValue) { var value = BsonTypeMapper.MapToDotNetValue(bsonValue); var list = value as List <object>; if (list != null) { return(list.Cast <List <object> >().ToDictionary(e => (Tkey)e[0], e => (Tvalue)e[1])); } return(value as Dictionary <Tkey, Tvalue>); }
public static T FindOneById <T>(this IMongoCollection <T> collection, BsonValue idValue) { var value = BsonTypeMapper.MapToDotNetValue(idValue); if (idValue == null) { throw new JarvisFrameworkEngineException("FindOneById wrapper needs not a BsonValue but a plain value to be specified"); } return(collection.Find(Builders <T> .Filter.Eq("_id", value)).SingleOrDefault()); }
public IEnumerable <IEnumerable <KeyValuePair <string, object> > > Find(string entityName, QueryObject query, QuerySortObject[] sort, int?skip, int?limit) { var mongoCollection = MongoStaticContext.Context.GetBsonCollection(RECORD_COLLECTION_PREFIX + entityName); var mongoQuery = ConvertQuery(query); var cursor = mongoCollection.Find(mongoQuery); if (sort != null && sort.Length > 0) { SortByBuilder sortBy = null; foreach (var s in sort) { if (s.SortType == QuerySortType.Ascending) { sortBy = sortBy == null?SortBy.Ascending(s.FieldName) : sortBy.Ascending(s.FieldName); } else { sortBy = sortBy == null?SortBy.Descending(s.FieldName) : sortBy.Descending(s.FieldName); } } cursor.SetSortOrder(sortBy); } if (skip.HasValue) { cursor.SetSkip(skip.Value); } if (limit.HasValue) { cursor.SetLimit(limit.Value); } List <List <KeyValuePair <string, object> > > result = new List <List <KeyValuePair <string, object> > >(); foreach (BsonDocument doc in cursor) { List <KeyValuePair <string, object> > record = new List <KeyValuePair <string, object> >(); foreach (var fieldName in doc.Names) { if (fieldName == "_id") { record.Add(new KeyValuePair <string, object>("id", BsonTypeMapper.MapToDotNetValue(doc["_id"]))); } else { record.Add(new KeyValuePair <string, object>(fieldName, ConvertBsonValueToObject(doc[fieldName]))); } } result.Add(record); } return(result); }
/// <summary> /// Assign the properties. /// </summary> public void AssignProperties() { // Get the current row. Dictionary <string, object> row = _BsonDocument.ToDictionary(); // Get all document property names. List <string> propertyName = new List <string>(); List <string> propertyType = new List <string>(); int index = 0; // For each property. foreach (KeyValuePair <string, object> id in row) { int current = 0; // Get the name. string name = id.Key; if (name.ToLower().Contains("_id")) { name = "Id"; } // Add the name. propertyName.Add(name); // Get the document values. IEnumerable <BsonValue> values = _BsonDocument.Values; // For each Bson value. foreach (BsonValue bsonValue in values) { // If the global and current index match. if (index == current) { // Map the Bson type tp .Net type. object netValue = BsonTypeMapper.MapToDotNetValue(bsonValue); propertyType.Add(netValue.GetType().ToString()); } // Increment the current index. current++; } // Crement global index. index++; } // Assign the values. _PropertyName = propertyName.ToArray(); _PropertyType = propertyType.ToArray(); }
public async Task <T> Get <T>(string name, CancellationToken cancellationToken) { FilterDefinition <BsonDocument> filter = Builders <BsonDocument> .Filter.Eq(NameField, name); BsonDocument doc = await _mongoCollection.Find(filter).SingleOrDefaultAsync(cancellationToken); if (doc != null && doc.TryGetValue(ValueField, out BsonValue value)) { return((T)BsonTypeMapper.MapToDotNetValue(value, BsonTypeMapperOptions.Defaults)); } return(default(T)); }
public static void p5_mongo_find(ApplicationContext context, ActiveEventArgs e) { // House cleaning using (new Utilities.ArgsRemover(e.Args, true)) { // Retrieving table name and running sanity check var tableName = e.Args.Get <string> (context); if (string.IsNullOrEmpty(tableName)) { throw new LambdaException("No table name supplied to [p5.mongo.find]", e.Args, context); } // Retrieving filter, defaulting to empty var filter = Filter.CreateFilter(context, e.Args); // Retrieving collection var collection = Database.Instance.MongoDatabase.GetCollection <BsonDocument> (tableName); // Running query var cursor = collection.Find(filter); // Sorting query cursor = SortCursor(context, e.Args, cursor); // Checking if we've got a [start] offset if (e.Args ["start"] != null) { cursor.Skip(e.Args.GetChildValue("start", context, 0)); } // Applying [count] int count = e.Args.GetChildValue("count", context, -1); // Looping through result set until [count] is reached int idxCount = 0; foreach (var idxDoc in cursor.ToEnumerable()) { // Making sure we return currently iterated document to caller var id = BsonTypeMapper.MapToDotNetValue(idxDoc.Elements.First(ix => ix.Name == "_id").Value); var idxNode = e.Args.Add(tableName, id).LastChild; // Parsing document, and stuffing results into idxNode, making sure we skip the "_id" element for main document DocumentParser.ParseDocument(context, idxNode, idxDoc, "_id"); // Checking if we've reached [count] if (++idxCount == count) { break; } } } }
private void DeserializeExtraElementValue( BsonDeserializationContext context, Dictionary <string, object> values, string elementName, BsonMemberMap extraElementsMemberMap) { var bsonReader = context.Reader; if (extraElementsMemberMap.MemberType == typeof(BsonDocument)) { BsonDocument extraElements; object obj; if (values.TryGetValue(extraElementsMemberMap.ElementName, out obj)) { extraElements = (BsonDocument)obj; } else { extraElements = new BsonDocument(); values.Add(extraElementsMemberMap.ElementName, extraElements); } var bsonValue = BsonValueSerializer.Instance.Deserialize(context); extraElements[elementName] = bsonValue; } else { IDictionary <string, object> extraElements; object obj; if (values.TryGetValue(extraElementsMemberMap.ElementName, out obj)) { extraElements = (IDictionary <string, object>)obj; } else { if (extraElementsMemberMap.MemberType == typeof(IDictionary <string, object>)) { extraElements = new Dictionary <string, object>(); } else { extraElements = (IDictionary <string, object>)Activator.CreateInstance(extraElementsMemberMap.MemberType); } values.Add(extraElementsMemberMap.ElementName, extraElements); } var bsonValue = BsonValueSerializer.Instance.Deserialize(context); extraElements[elementName] = BsonTypeMapper.MapToDotNetValue(bsonValue); } }
public object GetCollection(string constring, string db, string collection) { MongoClient dbClient = new MongoClient(constring); var dbase = dbClient.GetDatabase(db); var coll = dbase.GetCollection <BsonDocument>("Todo"); var returnDocument = coll.Find(new BsonDocument()).FirstOrDefault(); var dotNetObj = BsonTypeMapper.MapToDotNetValue(returnDocument); //var dotNetObj = returnDocument.ConvertAll(BsonTypeMapper.MapToDotNetValue); JsonConvert.SerializeObject(dotNetObj); return(dotNetObj); }