// public methods /// <summary> /// Returns the first matching element in the array specified by name. /// </summary> /// <param name="name">The name.</param> /// <param name="query">The query.</param> /// <returns>The build (so method calls can be chained).</returns> public FieldsBuilder ElemMatch(string name, IMongoQuery query) { var elemMatchDocument = new BsonDocument("$elemMatch", query.ToBsonDocument()); _document.Add(name, elemMatchDocument); return(this); }
/// <summary> /// Adds an $elemMatch test to the query. /// </summary> /// <param name="query">The query to match elements with.</param> /// <returns>The builder (so method calls can be chained).</returns> public QueryConditionList ElemMatch( IMongoQuery query ) { conditions.Add("$elemMatch", query.ToBsonDocument()); return(this); }
public WriteConcernResult Remove(IMongoQuery query, RemoveFlags flags, WriteConcern writeConcern, bool needResult) { var predicate = QueryCompiler.GetFunction(query.ToBsonDocument()); int documentsAffected = 0; for (int i = 0; i < Documents.Count; ++i) { if (!predicate(Documents[i])) { continue; } RemoveDocumentAt(i); ++documentsAffected; if ((flags & RemoveFlags.Single) > 0) { break; } --i; } return(needResult ? new WriteConcernResult(NewResponse(documentsAffected, false, null, null)) : null); }
private static BsonDocument buildMatchCondition(IReportSpecification specification) { IMongoQuery orClause = createSearchClauseForAnyFilter(specification); IMongoQuery typeNameClause = createSearchClauseForAnyType(specification); // Query.EQ("TypeName", specification.TrackerTypeName); IMongoQuery dateClause = Query.And(Query.GTE("TimeSlot", specification.FromDateUtc), Query.LTE("TimeSlot", specification.ToDateUtc)); var conditions = new BsonDocument(dateClause.ToBsonDocument()); conditions.AddRange(typeNameClause.ToBsonDocument()); if (orClause != null) { conditions.AddRange(orClause.ToBsonDocument()); } var match = new BsonDocument { { "$match", conditions } }; return(match); }
// Inserts a new document created from a query and an update and returns it. BsonDocument InsertNewDocument(IMongoQuery query, IMongoUpdate update) { var document = new BsonDocument(); UpdateCompiler.GetFunction((IConvertibleToBsonDocument)update, query.ToBsonDocument(), true)(document); InsertInternal(document); return(document); }
public override IEnumerable <BsonDocument> Group(IMongoQuery query, BsonJavaScript keyFunction, BsonDocument initial, BsonJavaScript reduce, BsonJavaScript finalize) { var sw = new Stopwatch(); sw.Start(); var result = base.Group(query, keyFunction, initial, reduce, finalize); sw.Stop(); var commandStringBuilder = new StringBuilder(1024); commandStringBuilder.AppendFormat("db.{0}.group({{keyf, reduce, initial", Name); if (query != null) { commandStringBuilder.Append(", cond"); } if (initial != null) { commandStringBuilder.Append(", initial"); } if (finalize != null) { commandStringBuilder.Append(", finalize"); } commandStringBuilder.Append("})"); commandStringBuilder.AppendFormat("\nkeyf = javascript"); commandStringBuilder.Append("\nreduce = javascript"); commandStringBuilder.AppendFormat("\ninitial = {0}", initial.ToBsonDocument()); if (query != null) { commandStringBuilder.AppendFormat("\ncond = {0}", query.ToBsonDocument()); } if (initial != null) { commandStringBuilder.AppendFormat("\ninitial = {0}", initial.ToBsonDocument()); } if (finalize != null) { commandStringBuilder.Append("\nfinalize = javascript"); } string commandString = commandStringBuilder.ToString(); ProfilerUtils.AddMongoTiming(commandString, sw.ElapsedMilliseconds, ExecuteType.Read); return(result); }
public static BsonDocument ToMatchDocument(this IMongoQuery query) { return(new BsonDocument { { "$match", query.ToBsonDocument() } }); }
public override WriteConcernResult Update(IMongoQuery query, IMongoUpdate update, MongoUpdateOptions options) { var sw = new Stopwatch(); sw.Start(); var result = base.Update(query, update, options); sw.Stop(); var commandStringBuilder = new StringBuilder(1024); commandStringBuilder.AppendFormat("db.{0}.update(query, update", Name); var optionsList = new List <string>(); if ((options.Flags & UpdateFlags.Upsert) == UpdateFlags.Upsert) { optionsList.Add("upsert: true"); } if ((options.Flags & UpdateFlags.Multi) == UpdateFlags.Multi) { optionsList.Add("multi: true"); } if (optionsList.Any()) { commandStringBuilder.AppendFormat("{{ {0} }}", string.Join(", ", optionsList)); } commandStringBuilder.Append(")"); if (query != null) { commandStringBuilder.AppendFormat("\nquery = {0}", query.ToBsonDocument()); } else { commandStringBuilder.Append("\nquery = {}"); } if (update != null) { commandStringBuilder.AppendFormat("\nupdate = {0}", update.ToBsonDocument()); } else { commandStringBuilder.Append("\nupdate = {}"); } string commandString = commandStringBuilder.ToString(); ProfilerUtils.AddMongoTiming(commandString, sw.ElapsedMilliseconds, ExecuteType.Update); return(result); }
public AggregationBuilder Match(IMongoQuery query) { if (query != null && query != Query.Null) { var newPipe = new BsonDocument { { "$match", query.ToBsonDocument() } }; pipeline.Add(newPipe); } return(this); }
/// <summary> /// Tests that at least one item of the named array element matches a query (see $elemMatch). /// </summary> /// <param name="name">The name of the element to test.</param> /// <param name="query">The query to match elements with.</param> /// <returns>An IMongoQuery.</returns> public static IMongoQuery ElemMatch(string name, IMongoQuery query) { if (name == null) { throw new ArgumentNullException("name"); } if (query == null) { throw new ArgumentNullException("query"); } var condition = new BsonDocument("$elemMatch", query.ToBsonDocument()); return(new QueryDocument(name, condition)); }
public CommandResult FullTextSearch <T>(string lang, string keyword, IMongoQuery query, IMongoFields fields, int limit) { var _cmd = new CommandDocument { { "text", MongoExtensions.GetCollectionName <T>() }, { "language", lang }, { "search", (keyword != "") ? keyword : "" }, { "filter", query.ToBsonDocument() }, { "project", fields.ToBsonDocument() }, { "limit", limit } }; var _result = Database.RunCommand(_cmd); return(_result); }
public override WriteConcernResult Remove(IMongoQuery query, RemoveFlags flags, WriteConcern writeConcern) { var sw = new Stopwatch(); sw.Start(); var result = base.Remove(query, flags, writeConcern); sw.Stop(); var commandStringBuilder = new StringBuilder(1024); commandStringBuilder.AppendFormat("db.{0}.remove", Name); if (query == null) { if ((flags & RemoveFlags.None) == RemoveFlags.None) { commandStringBuilder.Append("()"); } else if ((flags & RemoveFlags.Single) == RemoveFlags.Single) { commandStringBuilder.Append("({}, true)"); } } else { commandStringBuilder.Append("("); commandStringBuilder.AppendFormat("query"); if ((flags & RemoveFlags.Single) == RemoveFlags.Single) { commandStringBuilder.Append(", true"); } commandStringBuilder.Append(")"); commandStringBuilder.AppendFormat("\nquery = {0}", query.ToBsonDocument()); } string commandString = commandStringBuilder.ToString(); ProfilerUtils.AddMongoTiming(commandString, sw.ElapsedMilliseconds, ExecuteType.Create); return(result); }
public void UpdateTest() { IMongoQuery query = null; IMongoUpdate update = null; collection.Setup(c => c.Update(It.IsAny <IMongoQuery>(), It.IsAny <IMongoUpdate>())) .Callback <IMongoQuery, IMongoUpdate>((q, u) => { query = q; update = u; }).Returns(() => { return(new MongoMockResult()); }); var entity = new NamedEntity { name = "First" }; repository.Create(entity); var updateEntity = new NamedEntity { name = "Second" }; repository.Update(entity.id, updateEntity); Assert.IsNotNull(query); Assert.IsNotNull(update); Assert.AreEqual(entity.id, query.ToBsonDocument()["_id"].ToString()); var document = update.ToBsonDocument(); Assert.IsNotNull(document["$set"]["updated_at"]); Assert.AreEqual(updateEntity.name, document["$set"]["name"].AsString); Assert.AreEqual(2, document["$set"].AsBsonDocument.ElementCount); }
// public methods /// <summary> /// Returns the first matching element in the array specified by name. /// </summary> /// <param name="name">The name.</param> /// <param name="query">The query.</param> /// <returns>The build (so method calls can be chained).</returns> public FieldsBuilder ElemMatch(string name, IMongoQuery query) { var elemMatchDocument = new BsonDocument("$elemMatch", query.ToBsonDocument()); _document.Add(name, elemMatchDocument); return this; }
/// <summary> /// Tests that at least one item of the named array element matches a query (see $elemMatch). /// </summary> /// <param name="query">The query to match elements with.</param> /// <returns>The builder (so method calls can be chained).</returns> public QueryConditionList ElemMatch(IMongoQuery query) { if (query == null) { throw new ArgumentNullException("query"); } _conditions.Add("$elemMatch", query.ToBsonDocument()); return this; }
public NoSqlPipeline GeoNear(double[] location, string distanceField, IMongoQuery query) { return GeoNear(location, distanceField, new BsonElement("query", query.ToBsonDocument())); }
/// <summary> /// Tests that at least one item of the named array element matches a query (see $elemMatch). /// </summary> /// <param name="query">The query to match elements with.</param> /// <returns>The builder (so method calls can be chained).</returns> public QueryConditionList ElemMatch(IMongoQuery query) { _conditions.Add("$elemMatch", query.ToBsonDocument()); return this; }
IEnumerable <BsonDocument> QueryDocuments(IMongoQuery query) { return(Documents.Where(QueryCompiler.GetFunction(query.ToBsonDocument()))); }
/// <summary> /// Sets the validator. /// </summary> /// <param name="validator">The validator.</param> /// <returns>The builder (so method calls can be chained).</returns> public CollectionOptionsBuilder SetValidator(IMongoQuery validator) { _document["validator"] = validator.ToBsonDocument(); return(this); }
/// <summary> /// Sets the partial filter expression. /// </summary> /// <param name="value">The value.</param> /// <returns>The builder (so method calls can be chained).</returns> public IndexOptionsBuilder SetPartialFilterExpression(IMongoQuery value) { _document["partialFilterExpression"] = value.ToBsonDocument(); return(this); }
/// <summary> /// Tests that at least one item of the named array element matches a query (see $elemMatch). /// </summary> /// <param name="name">The name of the element to test.</param> /// <param name="query">The query to match elements with.</param> /// <returns>An IMongoQuery.</returns> public static IMongoQuery ElemMatch(string name, IMongoQuery query) { if (name == null) { throw new ArgumentNullException("name"); } if (query == null) { throw new ArgumentNullException("query"); } var condition = new BsonDocument("$elemMatch", query.ToBsonDocument()); return new QueryDocument(name, condition); }
public static IMongoQuery FormatIdElementForMongoQuery(IMongoQuery query) { return(new QueryDocument(FormatIdElementForBsonDocument(query.ToBsonDocument()))); }
/// <summary> /// Tests that the inverse of the query is true (see $not). /// </summary> /// <param name="query">The query.</param> /// <returns>An IMongoQuery.</returns> public static IMongoQuery Not(IMongoQuery query) { if (query == null) { throw new ArgumentNullException("query"); } var queryDocument = query.ToBsonDocument(); if (queryDocument.ElementCount == 1) { var elementName = queryDocument.GetElement(0).Name; switch (elementName) { case "$and": // there is no $nand and $not only works as a meta operator on a single operator so simulate $not using $nor return new QueryDocument("$nor", new BsonArray { queryDocument }); case "$or": return new QueryDocument("$nor", queryDocument[0].AsBsonArray); case "$nor": return new QueryDocument("$or", queryDocument[0].AsBsonArray); } var operatorDocument = queryDocument[0] as BsonDocument; if (operatorDocument != null && operatorDocument.ElementCount > 0) { var operatorName = operatorDocument.GetElement(0).Name; if (operatorDocument.ElementCount == 1) { switch (operatorName) { case "$exists": var boolValue = operatorDocument[0].AsBoolean; return new QueryDocument(elementName, new BsonDocument("$exists", !boolValue)); case "$in": var values = operatorDocument[0].AsBsonArray; return new QueryDocument(elementName, new BsonDocument("$nin", values)); case "$not": var predicate = operatorDocument[0]; return new QueryDocument(elementName, predicate); case "$ne": var comparisonValue = operatorDocument[0]; return new QueryDocument(elementName, comparisonValue); } if (operatorName[0] == '$') { // use $not as a meta operator on a single operator return new QueryDocument(elementName, new BsonDocument("$not", operatorDocument)); } } else { // $ref isn't an operator (it's the first field of a DBRef) if (operatorName[0] == '$' && operatorName != "$ref") { // $not only works as a meta operator on a single operator so simulate $not using $nor return new QueryDocument("$nor", new BsonArray { queryDocument }); } } } var operatorValue = queryDocument[0]; if (operatorValue.IsBsonRegularExpression) { return new QueryDocument(elementName, new BsonDocument("$not", operatorValue)); } // turn implied equality comparison into $ne return new QueryDocument(elementName, new BsonDocument("$ne", operatorValue)); } // $not only works as a meta operator on a single operator so simulate $not using $nor return new QueryDocument("$nor", new BsonArray { queryDocument }); }
public NoSqlPipeline GeoNear(double[] location, string distanceField, double maxDistance, int num, IMongoQuery query, string includeDocs, bool uniqueDocs) { return GeoNear(location, distanceField, new BsonElement[] { new BsonElement("maxDistance", maxDistance), new BsonElement("num", num), new BsonElement("query", query.ToBsonDocument()), new BsonElement("includeDocs", includeDocs), new BsonElement("uniqueDocs", uniqueDocs) }); }
internal static IEnumerable <BsonDocument> Query(IEnumerable <BsonDocument> documents, IDictionary <BsonValue, BsonDocument> dictionary, IMongoQuery query, IMongoSortBy sortBy, int skip, int first) { var queryDocument = query.ToBsonDocument(); BsonValue idSelector; if (dictionary != null && queryDocument != null && queryDocument.TryGetValue(MyValue.Id, out idSelector)) { documents = OptimisedDocuments(dictionary, idSelector); if (documents == null) { return new BsonDocument[] { } } ; } var queryableData = documents.AsQueryable <BsonDocument>(); var predicateBody = GetExpression(queryDocument); var expression = Expression.Call( typeof(Queryable), "Where", new Type[] { queryableData.ElementType }, queryableData.Expression, Expression.Lambda <Func <BsonDocument, bool> >(predicateBody, Data)); // #3 - use GetValue(string, <default>) because fields may be missing, GetValue(string) throws var miGetValue = typeof(BsonDocument).GetMethod("GetValue", new Type[] { typeof(string), typeof(BsonValue) }); if (sortBy != null) { var sortDocument = ((IConvertibleToBsonDocument)sortBy).ToBsonDocument(); for (int i = 0; i < sortDocument.ElementCount; ++i) { var element = sortDocument.GetElement(i); var selector = Expression.Call(Data, miGetValue, Expression.Constant(element.Name, typeof(string)), Expression.Constant(null, typeof(BsonValue))); string sortMethodName; if (i == 0) { sortMethodName = element.Value.AsInt32 > 0 ? "OrderBy" : "OrderByDescending"; } else { sortMethodName = element.Value.AsInt32 > 0 ? "ThenBy" : "ThenByDescending"; } expression = Expression.Call( typeof(Queryable), sortMethodName, new Type[] { queryableData.ElementType, typeof(BsonValue) }, expression, Expression.Lambda <Func <BsonDocument, BsonValue> >(selector, Data)); } } if (skip > 0) { expression = Expression.Call( typeof(Queryable), "Skip", new Type[] { queryableData.ElementType }, expression, Expression.Constant(skip, typeof(int))); } if (first > 0) { expression = Expression.Call( typeof(Queryable), "Take", new Type[] { queryableData.ElementType }, expression, Expression.Constant(first, typeof(int))); } return(queryableData.Provider.CreateQuery <BsonDocument>(expression)); } }
public NoSqlPipeline Match(IMongoQuery query) { var match = new BsonDocument() .Add(new BsonElement("$match", query.ToBsonDocument())); Pipeline.Add(match); return this; }
/// <summary> /// Tests that the inverse of the query is true (see $not). /// </summary> /// <param name="query">The query.</param> /// <returns>An IMongoQuery.</returns> public static IMongoQuery Not(IMongoQuery query) { if (query == null) { throw new ArgumentNullException("query"); } var queryDocument = query.ToBsonDocument(); if (queryDocument.ElementCount == 1) { var elementName = queryDocument.GetElement(0).Name; switch (elementName) { case "$and": // there is no $nand and $not only works as a meta operator on a single operator so simulate $not using $nor return(new QueryDocument("$nor", new BsonArray { queryDocument })); case "$or": return(new QueryDocument("$nor", queryDocument[0].AsBsonArray)); case "$nor": return(new QueryDocument("$or", queryDocument[0].AsBsonArray)); } var operatorDocument = queryDocument[0] as BsonDocument; if (operatorDocument != null && operatorDocument.ElementCount > 0) { var operatorName = operatorDocument.GetElement(0).Name; if (operatorDocument.ElementCount == 1) { switch (operatorName) { case "$exists": var boolValue = operatorDocument[0].AsBoolean; return(new QueryDocument(elementName, new BsonDocument("$exists", !boolValue))); case "$in": var values = operatorDocument[0].AsBsonArray; return(new QueryDocument(elementName, new BsonDocument("$nin", values))); case "$not": var predicate = operatorDocument[0]; return(new QueryDocument(elementName, predicate)); case "$ne": var comparisonValue = operatorDocument[0]; return(new QueryDocument(elementName, comparisonValue)); } if (operatorName[0] == '$') { // use $not as a meta operator on a single operator return(new QueryDocument(elementName, new BsonDocument("$not", operatorDocument))); } } else { // $ref isn't an operator (it's the first field of a DBRef) if (operatorName[0] == '$' && operatorName != "$ref") { // $not only works as a meta operator on a single operator so simulate $not using $nor return(new QueryDocument("$nor", new BsonArray { queryDocument })); } } } var operatorValue = queryDocument[0]; if (operatorValue.IsBsonRegularExpression) { return(new QueryDocument(elementName, new BsonDocument("$not", operatorValue))); } // turn implied equality comparison into $ne return(new QueryDocument(elementName, new BsonDocument("$ne", operatorValue))); } // $not only works as a meta operator on a single operator so simulate $not using $nor return(new QueryDocument("$nor", new BsonArray { queryDocument })); }
private FindAndModifyResult FindAndModifyImpl(IMongoQuery query, IMongoSortBy sortBy, bool remove, IMongoUpdate update, bool returnNew, IMongoFields fields, bool upsert) { var sw = new Stopwatch(); sw.Start(); var result = base.FindAndModify(query, sortBy, update, fields, returnNew, upsert); sw.Stop(); var commandStringBuilder = new StringBuilder(1024); commandStringBuilder.AppendFormat("db.{0}.findAndModify(query, sort, remove, update, new, fields, upsert)", Name); if (query != null) { commandStringBuilder.AppendFormat("\nquery = {0}", query.ToBsonDocument()); } else { commandStringBuilder.Append("\nquery = null"); } if (sortBy != null) { commandStringBuilder.AppendFormat("\nsort = {0}", sortBy.ToBsonDocument()); } else { commandStringBuilder.Append("\nsort = null"); } commandStringBuilder.AppendFormat("\nremove = {0}", remove ? "true" : "false"); if (update != null) { commandStringBuilder.AppendFormat("\nupdate = {0}", update.ToBsonDocument()); } else { commandStringBuilder.Append("\nupdate = null"); } commandStringBuilder.AppendFormat("\nnew = {0}", returnNew ? "true" : "false"); if (fields != null) { commandStringBuilder.AppendFormat("\nfields = {0}", fields.ToBsonDocument()); } else { commandStringBuilder.Append("\nfields = null"); } commandStringBuilder.AppendFormat("\nupsert = {0}", upsert ? "true" : "false"); string commandString = commandStringBuilder.ToString(); ProfilerUtils.AddMongoTiming(commandString, sw.ElapsedMilliseconds, ExecuteType.Update); return(result); }