/// <summary> /// Pushes a value to it's parent data stream on MongoDB. /// </summary> /// <param name="data"></param> private void PushProcessData(Value data) { //If Mongo unaccessible, ignore! if (!_mongoAccessible) return; //Merges all values then replaces the entire document. var collection = _db.GetCollection<Process>("ProcessData"); var filter = Builders<Process>.Filter.Eq("DeviceId", data.DeviceId); var result = collection.Find(filter).ToList(); if (result.Count > 0) { //Submit the returned Device and the new Value for commital. PushProcessData(result[0],data); } }
/// <summary> /// Push the Process object and the newest value to MongoDB. /// Finds the Device header in Mongo's ProcessData and appends /// the new value to it. /// </summary> private void PushProcessData(Process data, Value newValue = null) { //If Mongo unaccessible, ignore! if (!_mongoAccessible) return; //Merges all values then replaces the entire document. var collection = _db.GetCollection<Process>("ProcessData"); var filter = Builders<Process>.Filter.Eq("DeviceId", data.DeviceId); var result = collection.Find(filter).ToList(); if (result.Count > 0) { var entity = result[0]; data.ObjectId = entity.ObjectId; var currentVals = result[0].Values; var allValues = new List<Value>(); //If not null, add the new value to the device's collection. if (newValue != null) allValues.Add(newValue); allValues.AddRange(currentVals); allValues.AddRange(data.Values); data.Values = allValues; } var update = collection.ReplaceOne ( item => item.DeviceId == data.DeviceId, data, new UpdateOptions { IsUpsert = true } ); }
/// <summary> /// Posts the parametised Value object directly into the database. /// </summary> /// <param name="value"></param> public void AddNewValue(Value value) { if (!_mongoAccessible) return; try { _db.GetCollection<Value>("Values").InsertOne(value); PushProcessData(value); } catch (Exception e) { DebugOutput.Print( $"Could not store Value {value.ValueId}'s value ({value.StringValue}) in MongoDb. ", e.Message); } }