private CommandResult CreateCollection(IClientSessionHandle session, string collectionName, IMongoCollectionOptions options)
        {
            if (collectionName == null)
            {
                throw new ArgumentNullException("collectionName");
            }

            var                      collectionNamespace    = new CollectionNamespace(_namespace, collectionName);
            var                      messageEncoderSettings = GetMessageEncoderSettings();
            bool?                    autoIndexId            = null;
            bool?                    capped              = null;
            Collation                collation           = null;
            BsonDocument             indexOptionDefaults = null;
            int?                     maxDocuments        = null;
            long?                    maxSize             = null;
            bool?                    noPadding           = null;
            BsonDocument             storageEngine       = null;
            bool?                    usePowerOf2Sizes    = null;
            DocumentValidationAction?validationAction    = null;
            DocumentValidationLevel? validationLevel     = null;
            BsonDocument             validator           = null;

            if (options != null)
            {
                var optionsDocument = options.ToBsonDocument();

                BsonValue value;
                if (optionsDocument.TryGetValue("autoIndexId", out value))
                {
                    autoIndexId = value.ToBoolean();
                }
                if (optionsDocument.TryGetValue("capped", out value))
                {
                    capped = value.ToBoolean();
                }
                if (optionsDocument.TryGetValue("collation", out value))
                {
                    collation = Collation.FromBsonDocument(value.AsBsonDocument);
                }
                if (optionsDocument.TryGetValue("indexOptionDefaults", out value))
                {
                    indexOptionDefaults = value.AsBsonDocument;
                }
                if (optionsDocument.TryGetValue("max", out value))
                {
                    maxDocuments = value.ToInt32();
                }
                if (optionsDocument.TryGetValue("flags", out value))
                {
                    noPadding = ((CollectionUserFlags)value.ToInt32() & CollectionUserFlags.NoPadding) != 0;
                }
                if (optionsDocument.TryGetValue("size", out value))
                {
                    maxSize = value.ToInt64();
                }
                if (optionsDocument.TryGetValue("storageEngine", out value))
                {
                    storageEngine = value.AsBsonDocument;
                }
                if (optionsDocument.TryGetValue("flags", out value))
                {
                    usePowerOf2Sizes = ((CollectionUserFlags)value.ToInt32() & CollectionUserFlags.UsePowerOf2Sizes) != 0;
                }
                if (optionsDocument.TryGetValue("validationAction", out value))
                {
                    validationAction = (DocumentValidationAction)Enum.Parse(typeof(DocumentValidationAction), value.AsString, ignoreCase: true);
                }
                if (optionsDocument.TryGetValue("validationLevel", out value))
                {
                    validationLevel = (DocumentValidationLevel)Enum.Parse(typeof(DocumentValidationLevel), value.AsString, ignoreCase: true);
                }
                if (optionsDocument.TryGetValue("validator", out value))
                {
                    validator = value.AsBsonDocument;
                }
            }

            var operation = new CreateCollectionOperation(collectionNamespace, messageEncoderSettings)
            {
                AutoIndexId         = autoIndexId,
                Capped              = capped,
                Collation           = collation,
                IndexOptionDefaults = indexOptionDefaults,
                MaxDocuments        = maxDocuments,
                MaxSize             = maxSize,
                NoPadding           = noPadding,
                StorageEngine       = storageEngine,
                UsePowerOf2Sizes    = usePowerOf2Sizes,
                ValidationAction    = validationAction,
                ValidationLevel     = validationLevel,
                Validator           = validator,
                WriteConcern        = _settings.WriteConcern
            };

            var response = ExecuteWriteOperation(session, operation);

            return(new CommandResult(response));
        }
Beispiel #2
0
        private FindOperation <TResult> CreateAggregateToCollectionFindOperation <TResult>(BsonDocument outStage, IBsonSerializer <TResult> resultSerializer, AggregateOptions options)
        {
            CollectionNamespace outputCollectionNamespace;
            var stageName = outStage.GetElement(0).Name;

            switch (stageName)
            {
            case "$out":
            {
                var outValue = outStage[0];
                DatabaseNamespace outputDatabaseNamespace;
                string            outputCollectionName;
                if (outValue.IsString)
                {
                    outputDatabaseNamespace = _databaseNamespace;
                    outputCollectionName    = outValue.AsString;
                }
                else
                {
                    outputDatabaseNamespace = new DatabaseNamespace(outValue["db"].AsString);
                    outputCollectionName    = outValue["coll"].AsString;
                }
                outputCollectionNamespace = new CollectionNamespace(outputDatabaseNamespace, outputCollectionName);
            }
            break;

            case "$merge":
            {
                var mergeArguments = outStage[0].AsBsonDocument;
                DatabaseNamespace outputDatabaseNamespace;
                string            outputCollectionName;
                var into = mergeArguments["into"];
                if (into.IsString)
                {
                    outputDatabaseNamespace = _databaseNamespace;
                    outputCollectionName    = into.AsString;
                }
                else
                {
                    outputDatabaseNamespace = new DatabaseNamespace(into["db"].AsString);
                    outputCollectionName    = into["coll"].AsString;
                }
                outputCollectionNamespace = new CollectionNamespace(outputDatabaseNamespace, outputCollectionName);
            }
            break;

            default:
                throw new ArgumentException($"Unexpected stage name: {stageName}.");
            }

            // because auto encryption is not supported for non-collection commands.
            // So, an error will be thrown in the previous CreateAggregateToCollectionOperation step.
            // However, since we've added encryption configuration for CreateAggregateToCollectionOperation operation,
            // it's not superfluous to also add it here
            var messageEncoderSettings = GetMessageEncoderSettings();

            return(new FindOperation <TResult>(outputCollectionNamespace, resultSerializer, messageEncoderSettings)
            {
                BatchSize = options.BatchSize,
                Collation = options.Collation,
                MaxTime = options.MaxTime,
                ReadConcern = _settings.ReadConcern,
                RetryRequested = _client.Settings.RetryReads
            });
        }
        /// <summary>
        /// Creates a collection. MongoDB creates collections automatically when they are first used, so
        /// you only need to call this method if you want to provide non-default options.
        /// </summary>
        /// <param name="collectionName">The name of the collection.</param>
        /// <param name="options">Options for creating this collection (usually a CollectionOptionsDocument or constructed using the CollectionOptions builder).</param>
        /// <returns>A CommandResult.</returns>
        public virtual CommandResult CreateCollection(string collectionName, IMongoCollectionOptions options)
        {
            if (collectionName == null)
            {
                throw new ArgumentNullException("collectionName");
            }

            var          collectionNamespace    = new CollectionNamespace(_namespace, collectionName);
            var          messageEncoderSettings = GetMessageEncoderSettings();
            bool?        autoIndexId            = null;
            bool?        capped           = null;
            int?         maxDocuments     = null;
            int?         maxSize          = null;
            BsonDocument storageEngine    = null;
            bool?        usePowerOf2Sizes = null;

            if (options != null)
            {
                var optionsDocument = options.ToBsonDocument();

                BsonValue value;
                if (optionsDocument.TryGetValue("autoIndexId", out value))
                {
                    autoIndexId = value.ToBoolean();
                }
                if (optionsDocument.TryGetValue("capped", out value))
                {
                    capped = value.ToBoolean();
                }
                if (optionsDocument.TryGetValue("max", out value))
                {
                    maxDocuments = value.ToInt32();
                }
                if (optionsDocument.TryGetValue("size", out value))
                {
                    maxSize = value.ToInt32();
                }
                if (optionsDocument.TryGetValue("storageEngine", out value))
                {
                    storageEngine = value.AsBsonDocument;
                }
                if (optionsDocument.TryGetValue("flags", out value))
                {
                    usePowerOf2Sizes = value.ToInt32() == 1;
                }
            }

            var operation = new CreateCollectionOperation(collectionNamespace, messageEncoderSettings)
            {
                AutoIndexId      = autoIndexId,
                Capped           = capped,
                MaxDocuments     = maxDocuments,
                MaxSize          = maxSize,
                StorageEngine    = storageEngine,
                UsePowerOf2Sizes = usePowerOf2Sizes
            };

            var response = ExecuteWriteOperation(operation);

            return(new CommandResult(response));
        }
        public override async Task <IAsyncCursor <TResult> > MapReduceAsync <TResult>(BsonJavaScript map, BsonJavaScript reduce, MapReduceOptions <TDocument, TResult> options = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            Ensure.IsNotNull(map, "map");
            Ensure.IsNotNull(reduce, "reduce");

            options = options ?? new MapReduceOptions <TDocument, TResult>();
            var outputOptions    = options.OutputOptions ?? MapReduceOutputOptions.Inline;
            var resultSerializer = ResolveResultSerializer <TResult>(options.ResultSerializer);

            if (outputOptions == MapReduceOutputOptions.Inline)
            {
                var operation = new MapReduceOperation <TResult>(
                    _collectionNamespace,
                    map,
                    reduce,
                    resultSerializer,
                    _messageEncoderSettings)
                {
                    Filter           = options.Filter == null ? null : options.Filter.Render(_documentSerializer, _settings.SerializerRegistry),
                    FinalizeFunction = options.Finalize,
                    JavaScriptMode   = options.JavaScriptMode,
                    Limit            = options.Limit,
                    MaxTime          = options.MaxTime,
                    Scope            = options.Scope,
                    Sort             = options.Sort == null ? null : options.Sort.Render(_documentSerializer, _settings.SerializerRegistry),
                    Verbose          = options.Verbose
                };

                return(await ExecuteReadOperation(operation, cancellationToken).ConfigureAwait(false));
            }
            else
            {
                var collectionOutputOptions = (MapReduceOutputOptions.CollectionOutput)outputOptions;
                var databaseNamespace       = collectionOutputOptions.DatabaseName == null ?
                                              _collectionNamespace.DatabaseNamespace :
                                              new DatabaseNamespace(collectionOutputOptions.DatabaseName);
                var outputCollectionNamespace = new CollectionNamespace(databaseNamespace, collectionOutputOptions.CollectionName);

                var operation = new MapReduceOutputToCollectionOperation(
                    _collectionNamespace,
                    outputCollectionNamespace,
                    map,
                    reduce,
                    _messageEncoderSettings)
                {
                    Filter           = options.Filter == null ? null : options.Filter.Render(_documentSerializer, _settings.SerializerRegistry),
                    FinalizeFunction = options.Finalize,
                    JavaScriptMode   = options.JavaScriptMode,
                    Limit            = options.Limit,
                    MaxTime          = options.MaxTime,
                    NonAtomicOutput  = collectionOutputOptions.NonAtomic,
                    Scope            = options.Scope,
                    OutputMode       = collectionOutputOptions.OutputMode,
                    ShardedOutput    = collectionOutputOptions.Sharded,
                    Sort             = options.Sort == null ? null : options.Sort.Render(_documentSerializer, _settings.SerializerRegistry),
                    Verbose          = options.Verbose
                };

                await ExecuteWriteOperation(operation, cancellationToken).ConfigureAwait(false);

                var findOperation = new FindOperation <TResult>(
                    outputCollectionNamespace,
                    resultSerializer,
                    _messageEncoderSettings)
                {
                    MaxTime = options.MaxTime
                };

                // we want to delay execution of the find because the user may
                // not want to iterate the results at all...
                var deferredCursor = new DeferredAsyncCursor <TResult>(ct => ExecuteReadOperation(findOperation, ReadPreference.Primary, ct));
                return(await Task.FromResult(deferredCursor).ConfigureAwait(false));
            }
        }
        public void DatabaseName_should_report_the_provided_name()
        {
            var subject = new CollectionNamespace("test", "foo");

            subject.DatabaseNamespace.DatabaseName.Should().Be("test");
        }
Beispiel #6
0
        // public methods
        /// <inheritdoc />
        protected override ChangeStreamDocument <TDocument> DeserializeValue(BsonDeserializationContext context, BsonDeserializationArgs args)
        {
            var reader = context.Reader;

            CollectionNamespace           collectionNamespace = null;
            BsonDocument                  documentKey         = null;
            TDocument                     fullDocument        = default(TDocument);
            BsonDocument                  resumeToken         = null;
            ChangeStreamOperationType?    operationType       = null;
            ChangeStreamUpdateDescription updateDescription   = null;

            reader.ReadStartDocument();
            while (reader.ReadBsonType() != 0)
            {
                var fieldName = reader.ReadName();
                switch (fieldName)
                {
                case "_id":
                    resumeToken = BsonDocumentSerializer.Instance.Deserialize(context);
                    break;

                case "ns":
                    collectionNamespace = DeserializeCollectionNamespace(reader);
                    break;

                case "documentKey":
                    documentKey = BsonDocumentSerializer.Instance.Deserialize(context);
                    break;

                case "fullDocument":
                    if (reader.CurrentBsonType == BsonType.Null)
                    {
                        reader.ReadNull();
                        fullDocument = default(TDocument);
                    }
                    else
                    {
                        fullDocument = _documentSerializer.Deserialize(context);
                    }
                    break;

                case "operationType":
                    operationType = __operationTypeSerializer.Deserialize(context);
                    break;

                case "updateDescription":
                    updateDescription = __updateDescriptionSerializer.Deserialize(context);
                    break;

                default:
                    throw new FormatException($"Invalid field name: \"{fieldName}\".");
                }
            }
            reader.ReadEndDocument();

            return(new ChangeStreamDocument <TDocument>(
                       resumeToken,
                       operationType.Value,
                       collectionNamespace,
                       documentKey,
                       updateDescription,
                       fullDocument));
        }
 public void IsValid_should_return_the_correct_result(string name, bool valid)
 {
     CollectionNamespace.IsValid(name).Should().Be(valid);
 }
        public void FromFullName_should_throw_an_argument_null_exception_if_full_name_is_null()
        {
            Action act = () => CollectionNamespace.FromFullName(null);

            act.ShouldThrow <ArgumentNullException>();
        }
        public void FullName_should_report_the_provided_name()
        {
            var subject = new CollectionNamespace("test", "foo");

            subject.FullName.Should().Be("test.foo");
        }
        public void ToString_should_return_the_name()
        {
            var subject = CollectionNamespace.FromFullName("test.foo");

            subject.ToString().Should().Be("test.foo");
        }
 private FindOperation <TResult> CreateMapReduceOutputToCollectionFindOperation <TResult>(MapReduceOptions <TDocument, TResult> options, CollectionNamespace outputCollectionNamespace, IBsonSerializer <TResult> resultSerializer)
 {
     return(new FindOperation <TResult>(
                outputCollectionNamespace,
                resultSerializer,
                _messageEncoderSettings)
     {
         Collation = options.Collation,
         MaxTime = options.MaxTime,
         ReadConcern = _settings.ReadConcern
     });
 }
 // constructors
 public MongoCollectionImpl(IMongoDatabase database, CollectionNamespace collectionNamespace, MongoCollectionSettings settings, ICluster cluster, IOperationExecutor operationExecutor)
     : this(database, collectionNamespace, settings, cluster, operationExecutor, Ensure.IsNotNull(settings, "settings").SerializerRegistry.GetSerializer <TDocument>())
 {
 }
Beispiel #13
0
        /// <summary>
        /// Creates a collection. MongoDB creates collections automatically when they are first used, so
        /// you only need to call this method if you want to provide non-default options.
        /// </summary>
        /// <param name="collectionName">The name of the collection.</param>
        /// <param name="options">Options for creating this collection (usually a CollectionOptionsDocument or constructed using the CollectionOptions builder).</param>
        /// <returns>A CommandResult.</returns>
        public virtual CommandResult CreateCollection(string collectionName, IMongoCollectionOptions options)
        {
            if (collectionName == null)
            {
                throw new ArgumentNullException(nameof(collectionName));
            }

            var                      collectionNamespace    = new CollectionNamespace(_namespace, collectionName);
            var                      messageEncoderSettings = GetMessageEncoderSettings();
            bool?                    autoIndexId            = null;
            bool?                    capped = null;
            BsonDocument             indexOptionDefaults = null;
            int?                     maxDocuments        = null;
            long?                    maxSize             = null;
            BsonDocument             storageEngine       = null;
            bool?                    usePowerOf2Sizes    = null;
            DocumentValidationAction?validationAction    = null;
            DocumentValidationLevel? validationLevel     = null;
            BsonDocument             validator           = null;

            if (options != null)
            {
                var optionsDocument = options.ToBsonDocument();

                BsonValue value;
                if (optionsDocument.TryGetValue("autoIndexId", out value))
                {
                    autoIndexId = value.ToBoolean();
                }
                if (optionsDocument.TryGetValue("capped", out value))
                {
                    capped = value.ToBoolean();
                }
                if (optionsDocument.TryGetValue("indexOptionDefaults", out value))
                {
                    indexOptionDefaults = value.AsBsonDocument;
                }
                if (optionsDocument.TryGetValue("max", out value))
                {
                    maxDocuments = value.ToInt32();
                }
                if (optionsDocument.TryGetValue("size", out value))
                {
                    maxSize = value.ToInt64();
                }
                if (optionsDocument.TryGetValue("storageEngine", out value))
                {
                    storageEngine = value.AsBsonDocument;
                }
                if (optionsDocument.TryGetValue("flags", out value))
                {
                    usePowerOf2Sizes = value.ToInt32() == 1;
                }
                if (optionsDocument.TryGetValue("validationAction", out value))
                {
                    validationAction = (DocumentValidationAction)Enum.Parse(typeof(DocumentValidationAction), value.AsString, ignoreCase: true);
                }
                if (optionsDocument.TryGetValue("validationLevel", out value))
                {
                    validationLevel = (DocumentValidationLevel)Enum.Parse(typeof(DocumentValidationLevel), value.AsString, ignoreCase: true);
                }
                if (optionsDocument.TryGetValue("validator", out value))
                {
                    validator = value.AsBsonDocument;
                }
            }

            var operation = new CreateCollectionOperation(collectionNamespace, messageEncoderSettings)
            {
                AutoIndexId         = autoIndexId,
                Capped              = capped,
                IndexOptionDefaults = indexOptionDefaults,
                MaxDocuments        = maxDocuments,
                MaxSize             = maxSize,
                StorageEngine       = storageEngine,
                UsePowerOf2Sizes    = usePowerOf2Sizes,
                ValidationAction    = validationAction,
                ValidationLevel     = validationLevel,
                Validator           = validator
            };

            var response = ExecuteWriteOperation(operation);

            return(new CommandResult(response));
        }
 public void CollectionUsingTestSetUp()
 {
     _collectionNamespace = new CollectionNamespace(DatabaseNamespace, GetCollectionName());
     CreateCollection();
 }
 protected List <BsonDocument> ReadAll(CollectionNamespace collectionNamespace = null, MessageEncoderSettings messageEncoderSettings = null)
 {
     return(ReadAll <BsonDocument>(BsonDocumentSerializer.Instance, collectionNamespace, messageEncoderSettings));
 }