public TestClass( BsonDocumentWrapper value ) { this.B = value; this.V = value; }
/// <summary> /// Sets the optional query that filters which documents are sent to the map function (also useful in combination with SetSortOrder and SetLimit). /// </summary> /// <param name="query">The query.</param> /// <returns>The builder (so method calls can be chained).</returns> public MapReduceOptionsBuilder SetQuery(IMongoQuery query) { _document["query"] = BsonDocumentWrapper.Create(query); return(this); }
/// <summary> /// Sets a scope that contains variables that can be accessed by the map, reduce and finalize functions. /// </summary> /// <param name="scope">The scope.</param> /// <returns>The builder (so method calls can be chained).</returns> public MapReduceOptionsBuilder SetScope(IMongoScope scope) { _document["scope"] = BsonDocumentWrapper.Create(scope); return(this); }
protected IMongoQuery WrapQuery(IMongoQuery query, BsonDocument options, ReadPreference readPreference, bool forShardRouter) { BsonDocument formattedReadPreference = null; if (forShardRouter && readPreference != null && readPreference.ReadPreferenceMode != ReadPreferenceMode.Primary) { BsonArray tagSetsArray = null; if (readPreference.TagSets != null) { tagSetsArray = new BsonArray(); foreach (var tagSet in readPreference.TagSets) { var tagSetDocument = new BsonDocument(); foreach (var tag in tagSet) { tagSetDocument.Add(tag.Name, tag.Value); } tagSetsArray.Add(tagSetDocument); } } if (tagSetsArray != null || readPreference.ReadPreferenceMode != ReadPreferenceMode.SecondaryPreferred) { formattedReadPreference = new BsonDocument { { "mode", MongoUtils.ToCamelCase(readPreference.ReadPreferenceMode.ToString()) }, { "tags", tagSetsArray, tagSetsArray != null } // optional }; } } if (options == null && formattedReadPreference == null) { return(query); } else { var queryDocument = (query == null) ? (BsonValue) new BsonDocument() : BsonDocumentWrapper.Create(query); var wrappedQuery = new QueryDocument { { "$query", queryDocument }, { "$readPreference", formattedReadPreference, formattedReadPreference != null }, // only if sending query to a mongos }; wrappedQuery.Merge(options); return(wrappedQuery); } }
private IMongoQuery WrapQuery() { BsonDocument formattedReadPreference = null; if (_serverInstance.InstanceType == MongoServerInstanceType.ShardRouter && _readPreference.ReadPreferenceMode != ReadPreferenceMode.Primary) { BsonArray tagSetsArray = null; if (_readPreference.TagSets != null) { tagSetsArray = new BsonArray(); foreach (var tagSet in _readPreference.TagSets) { var tagSetDocument = new BsonDocument(); foreach (var tag in tagSet) { tagSetDocument.Add(tag.Name, tag.Value); } tagSetsArray.Add(tagSetDocument); } } if (tagSetsArray != null || _readPreference.ReadPreferenceMode != ReadPreferenceMode.SecondaryPreferred) { formattedReadPreference = new BsonDocument { { "mode", MongoUtils.ToCamelCase(_readPreference.ReadPreferenceMode.ToString()) }, { "tags", tagSetsArray, tagSetsArray != null } // optional }; } } if (_cursor.Options == null && formattedReadPreference == null) { return(_cursor.Query); } else { var query = (_cursor.Query == null) ? (BsonValue) new BsonDocument() : BsonDocumentWrapper.Create(_cursor.Query); var wrappedQuery = new QueryDocument { { "$query", query }, { "$readPreference", formattedReadPreference, formattedReadPreference != null }, // only if sending query to a mongos }; wrappedQuery.Merge(_cursor.Options); return(wrappedQuery); } }
private BsonDocument WrapCommandForQueryMessage(BsonDocument command, ConnectionDescription connectionDescription, out bool messageContainsSessionId, out bool secondaryOk) { messageContainsSessionId = false; var extraElements = new List <BsonElement>(); if (_session.Id != null) { var areSessionsSupported = connectionDescription.IsMasterResult.LogicalSessionTimeout.HasValue || connectionDescription.IsMasterResult.ServiceId.HasValue; if (areSessionsSupported) { var lsid = new BsonElement("lsid", _session.Id); extraElements.Add(lsid); messageContainsSessionId = true; } else { if (!_session.IsImplicit) { throw new MongoClientException("Sessions are not supported."); } } } if (_serverApi != null) { extraElements.Add(new BsonElement("apiVersion", _serverApi.Version.ToString())); if (_serverApi.Strict.HasValue) { extraElements.Add(new BsonElement("apiStrict", _serverApi.Strict.Value)); } if (_serverApi.DeprecationErrors.HasValue) { extraElements.Add(new BsonElement("apiDeprecationErrors", _serverApi.DeprecationErrors.Value)); } } if (_session.ClusterTime != null) { var clusterTime = new BsonElement("$clusterTime", _session.ClusterTime); extraElements.Add(clusterTime); } #pragma warning disable 618 Action <BsonWriterSettings> writerSettingsConfigurator = null; if (BsonDefaults.GuidRepresentationMode == GuidRepresentationMode.V2) { writerSettingsConfigurator = s => s.GuidRepresentation = GuidRepresentation.Unspecified; } #pragma warning restore 618 var appendExtraElementsSerializer = new ElementAppendingSerializer <BsonDocument>(BsonDocumentSerializer.Instance, extraElements, writerSettingsConfigurator); var commandWithExtraElements = new BsonDocumentWrapper(command, appendExtraElementsSerializer); var serverType = connectionDescription != null ? connectionDescription.IsMasterResult.ServerType : ServerType.Unknown; var readPreferenceDocument = QueryHelper.CreateReadPreferenceDocument(serverType, _readPreference, out secondaryOk); var wrappedCommand = new BsonDocument { { "$query", commandWithExtraElements }, { "$readPreference", readPreferenceDocument, readPreferenceDocument != null } }; if (_additionalOptions != null) { wrappedCommand.Merge(_additionalOptions, overwriteExistingElements: false); } if (wrappedCommand.ElementCount == 1) { return(wrappedCommand["$query"].AsBsonDocument); } else { return(wrappedCommand); } }
public async void Update(Department department) { document = BsonDocumentWrapper.Create(department); await collection.FindOneAndUpdateAsync(dep => dep.ID == department.ID, document); }
public void SaveOrUpdate <TEntity>(TEntity entity) where TEntity : class, IEntity, new() { var id = entity.TryGetValue("Id"); if (GetById <TEntity>(id) == null) { Save(entity); return; } var update = new UpdateBuilder(); foreach (var property in typeof(TEntity).GetProperties(BindingFlags.Public | BindingFlags.Instance) .Where(r => !r.Name.EqualsWithInvariant("Id"))) { var value = property.GetValue(entity, null); BsonValue bsonValue = BsonNull.Value; if (value != null) { var type = (property.PropertyType.IsGenericType && property.PropertyType.GetGenericTypeDefinition() == typeof(Nullable <>)) ? property.PropertyType.GetGenericArguments()[0] : property.PropertyType; if (type == typeof(string)) { bsonValue = new BsonString(value.ToString()); } else if (type == typeof(bool)) { bsonValue = new BsonBoolean((bool)value); } else if (type == typeof(DateTime)) { bsonValue = new BsonDateTime((DateTime)value); } else if (type == typeof(long)) { bsonValue = new BsonInt64((long)value); } else if (type == typeof(int)) { bsonValue = new BsonInt32((int)value); } else if (type == typeof(byte[])) { bsonValue = new BsonBinaryData((byte[])value); } else if (type == typeof(Guid)) { bsonValue = new BsonBinaryData((Guid)value); } else if (type.IsEnum) { bsonValue = new BsonString(value.ToString()); } else if (type.IsImplement <IEnumerable>()) { bsonValue = new BsonArray((IEnumerable)value); } else if (type.IsClass && type.IsImplement <IEntity>()) { bsonValue = new BsonDocumentWrapper(value); } else { throw new ArgumentOutOfRangeException("propertyType {0} does not bson value".F(type)); } } update.Set(property.Name, bsonValue); } GetCollection <TEntity>().Update(MongoDB.Driver.Builders.Query <TEntity> .EQ(r => r.Id, id), update); }
/// <summary> /// Sets the sort order (useful in combination with SetLimit, your map function should not depend on the order the documents are sent to it). /// </summary> /// <param name="sortBy">The sort order.</param> /// <returns>The builder (so method calls can be chained).</returns> public MapReduceOptionsBuilder SetSortOrder(IMongoSortBy sortBy) { _document["sort"] = BsonDocumentWrapper.Create(sortBy); return(this); }
public void TestCreateMultipleWithNominalTypeAndNullValues() { Assert.Throws <ArgumentNullException>(() => { var wrappers = BsonDocumentWrapper.CreateMultiple(typeof(C), null); }); }
public void TestConstructorWithNullNominalTypeAndObjectAndIsUpdateDocument() { Assert.Throws <ArgumentNullException>(() => { var wrapper = new BsonDocumentWrapper(null, _c, false); }); }
public void TestCreateMultipleWithNullNominalTypeAndValues() { Assert.Throws <ArgumentNullException>(() => { var wrappers = BsonDocumentWrapper.CreateMultiple(null, new C[] { _c, null }); }); }
public void TestCreateMultipleGenericWithNullValues() { Assert.Throws <ArgumentNullException>(() => { var wrappers = BsonDocumentWrapper.CreateMultiple <C>(null); }); }
public void TestCreateWithNullNominalTypeAndValueAndIsUpdateDocument() { Assert.Throws <ArgumentNullException>(() => { var wrapper = BsonDocumentWrapper.Create(null, _c, false); }); }
private BsonValue SerializeMetadata(Dictionary <String, Object> metadata) { return(BsonDocumentWrapper.Create(metadata)); }
/// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> /// <param name="collection"></param> /// <param name="filter"></param> /// <param name="projection"></param> private void Apply <T>(IMongoCollection <T> collection, FilterDefinition <T> filter, ProjectionDefinition <T> projection) { filter = CreateFilters <T>(Filter, filter); if (IsAggregate) { var sortB = Builders <T> .Sort; SortDefinition <T> sort = null; foreach (var item in Order) { switch (item.Direction.ToString()) { case "-": { if (sort == null) { sort = sortB.Descending(item.Property); } else { sort = sort.Descending(item.Property); } break; } case "+": { if (sort == null) { sort = sortB.Ascending(item.Property); } else { sort = sort.Ascending(item.Property); } break; } } } var Group = BsonDocumentWrapper.Parse(JsonConvert.SerializeObject(GroupBy)); IAggregateFluent <T> query = null; var options = new AggregateOptions(); if (sort != null) { query = collection.Aggregate().Match(filter).Sort(sort).Group <T>(Group).Project <T>(BsonDocumentWrapper.Parse("{'id':'$_id','count':'$count'}")); } else { query = collection.Aggregate().Match(filter).Group <T>(Group).Project <T>(BsonDocumentWrapper.Parse("{'id':'$_id','count':'$count'}")); } Data = query.ToList <T>(); } else { IFindFluent <T, T> query = null; if (filter != null) { query = collection.Find(filter); } else { query = collection.Find(x => true); } if (projection != null) { query = query.Project <T>(projection); } var sortB = Builders <T> .Sort; SortDefinition <T> sort = null; foreach (var item in Order) { switch (item.Direction.ToString()) { case "-": { if (sort == null) { sort = sortB.Descending(item.Property); } else { sort = sort.Descending(item.Property); } break; } case "+": { if (sort == null) { sort = sortB.Ascending(item.Property); } else { sort = sort.Ascending(item.Property); } break; } } } if (sort != null) { query.Sort(sort); } PageSize = PageSize ?? 1; RecordCount = query.Count(); if (PageSize != int.MaxValue) { PageCount = (RecordCount / PageSize); PageCount += (PageCount < ((float)RecordCount / (float)PageSize)) ? 1 : 0; Data = query.Skip((PageIndex - 1) * PageSize).Limit(PageSize).ToList <T>(); } else { PageCount = 1; Data = query.ToList <T>(); } } }