/* Copyright 2015-present MongoDB Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using MongoDB.Bson;
using MongoDB.Bson.Serialization;
using MongoDB.Driver.Core.Misc;
namespace MongoDB.Driver.Linq
{
///
/// A model for a queryable to be executed using the aggregation framework.
///
/// The type of the output.
public sealed class AggregateQueryableExecutionModel : QueryableExecutionModel
{
private readonly IReadOnlyList _stages;
private readonly IBsonSerializer _outputSerializer;
internal AggregateQueryableExecutionModel(IEnumerable stages, IBsonSerializer outputSerializer)
{
_stages = (Ensure.IsNotNull(stages, nameof(stages)) as IReadOnlyList) ?? stages.ToList();
_outputSerializer = Ensure.IsNotNull(outputSerializer, nameof(outputSerializer));
}
///
/// Gets the stages.
///
public IEnumerable Stages
{
get { return _stages; }
}
///
/// Gets the output serializer.
///
public IBsonSerializer OutputSerializer
{
get { return _outputSerializer; }
}
///
/// Gets the type of the output.
///
public override Type OutputType
{
get { return _outputSerializer.ValueType; }
}
///
/// Returns a that represents this instance.
///
///
/// A that represents this instance.
///
public override string ToString()
{
var sb = new StringBuilder("aggregate([");
if (_stages.Count > 0)
{
sb.Append(string.Join(", ", _stages.Select(x => x.ToString())));
}
sb.Append("])");
return sb.ToString();
}
internal override object Execute(IMongoCollection collection, AggregateOptions options)
{
var pipeline = CreatePipeline();
return collection.Aggregate(pipeline, options, CancellationToken.None);
}
internal override Task ExecuteAsync(IMongoCollection collection, AggregateOptions options, CancellationToken cancellationToken)
{
var pipeline = CreatePipeline();
return collection.AggregateAsync(pipeline, options, cancellationToken);
}
private BsonDocumentStagePipelineDefinition CreatePipeline()
{
return new BsonDocumentStagePipelineDefinition(
_stages,
_outputSerializer);
}
}
}