public IEnumerable<IDictionary<string, object>> Find(MongoCollection<BsonDocument> collection, SimpleQuery query, out IEnumerable<SimpleQueryClauseBase> unhandledClauses) { var builder = MongoQueryBuilder.BuildFrom(query); unhandledClauses = builder.UnprocessedClauses; if (builder.IsTotalCountQuery) { long count; if (builder.Criteria == null) count = collection.Count(); else count = collection.Count(_expressionFormatter.Format(builder.Criteria)); //TODO: figure out how to make count a long builder.SetTotalCount((int)count); } if (!builder.SkipCount.HasValue && builder.TakeCount.HasValue && builder.TakeCount.Value == 1) return new[] { FindOne(collection, builder.Criteria) }; var cursor = CreateCursor(collection, builder.Criteria); ApplyFields(cursor, builder.Columns); ApplySorting(cursor, builder.Order); ApplySkip(cursor, builder.SkipCount); ApplyTake(cursor, builder.TakeCount); var aliases = builder.Columns.OfType<ObjectReference>().ToDictionary(x => ExpressionFormatter.GetFullName(x), x => x.GetAlias()); return cursor.Select(x => x.ToSimpleDictionary(aliases)); }
/// <summary> /// Demo inserting multiple document into collection. /// </summary> /// <param name="orders">The orders.</param> private static void CreateAndInsertMultipleDocumentIntoCollection(MongoCollection<Order> orders) { Console.WriteLine("\n\n======= Insert Multiple Documents ======="); Console.WriteLine(string.Format("Document Count Before Insert: [ {0} ]", orders.Count())); // Create new orders. var order1 = new Order { OrderAmount = 100.23, CustomerName = "Bugs Bunny" }; var order2 = new Order { OrderAmount = 0.01, CustomerName = "Daffy Duck" }; IEnumerable<Order> orderList = new List<Order> { order1, order2 }; // Insert an IEnumerable. orders.InsertBatch(orderList); Console.WriteLine(string.Format("Inserted: {0}", order1)); Console.WriteLine(string.Format("Inserted: {0}", order2)); Console.WriteLine(string.Format("Document Count After Insert: [ {0} ]", orders.Count())); }
/// <summary> /// Demo deleting documents from collection. /// </summary> /// <param name="orders">The orders.</param> static void DeleteAllDocumentsFromCollection( MongoCollection< Order > collection ) { Console.WriteLine( "\n\n======= Delete Documents =======" ); Console.WriteLine( string.Format( "Document Count Before Delete: [ {0} ]", collection.Count() ) ); // Delete documents matching a criteria. collection.Remove( new {CustomerName = "Elmer Fudd"} ); Console.WriteLine( string.Format( "Document Count After Deleting Elmer Fudd: [ {0} ]", collection.Count() ) ); // Delete all docs. collection.Remove( new {} ); Console.WriteLine( "Deleted all docs" ); Console.WriteLine( string.Format( "Document Count After Deleting All Docs: [ {0} ]", collection.Count() ) ); }
public static void CoverDB(string player, MongoCollection oldPlayer, MongoCollection newPlayer) { Console.WriteLine("正在合并:" + player); int show = 0; int count = 0; var dates = oldPlayer.FindAllAs<BsonDocument>(); foreach (var v in dates) { BsonValue key; if (v.TryGetValue("_id", out key)) { if (newPlayer.Count(Query.EQ("_id", key)) <= 0) { count++; newPlayer.Save(v); } } show++; if (show % 1000 == 0) { Console.WriteLine("正在合并:" + show); } } Console.WriteLine(player + ":" + count); }
public void ReloadExisting() { connectionString = "mongodb://localhost/?safe=true"; server = MongoServer.Create(connectionString); habraDb = server.GetDatabase("habr", SafeMode.True); posts = habraDb.GetCollection<Post>("posts"); existedBeforeCount = posts.Count(); using (client = new WebClient()) { client.Encoding = Encoding.UTF8; foreach (var post in posts.FindAll()) { try { Console.Clear(); Console.WriteLine(string.Format("Reloaded: {0} posts of {1} possible", reloadedCount, existedBeforeCount)); Console.WriteLine("Processing: " + post.Url); Console.WriteLine("Loading..."); string pageContent = client.DownloadString(post.Url); Console.WriteLine("Parsing..."); ParsePostPage(post.Url, pageContent); } catch { } } } }
public void DownloadNew() { connectionString = "mongodb://localhost/?safe=true"; server = MongoServer.Create(connectionString); habraDb = server.GetDatabase("habr", SafeMode.True); posts = habraDb.GetCollection<Post>("posts"); existedBeforeCount = posts.Count(); int postListPage = 1; while (downloadedCount < NEEDED_POST_COUNT) { using (client = new WebClient()) { client.Encoding = Encoding.UTF8; try { string url = "http://habrahabr.ru/posts/collective/"; if (postListPage > 1) url += string.Format("page{0}/", postListPage); string pageContent = client.DownloadString(url); ParsePostListPage(pageContent); postListPage++; } catch { } } } }
/// <summary> /// Inserts a new document. /// </summary> /// <param name="collection">The orders.</param> private static void CreateAndInsertSingleDocumentIntoCollection(MongoCollection<Order> collection) { Console.WriteLine("\n\n======= Insert Multiple Documents ======="); Console.WriteLine(string.Format("Document Count Before Insert: [ {0} ]", collection.Count())); // Create a new order. var order = new Order() { OrderAmount = 57.22, CustomerName = "Elmer Fudd" }; // Add the new order to the mongo orders colleciton. collection.Insert(order); Console.WriteLine(string.Format("Inserted: {0}", order)); Console.WriteLine(string.Format("Document Count After Insert: [ {0} ]", collection.Count())); }
public void TestInsertForClassWithIdSucceeds() { collection.RemoveAll(); var c = new C { Id = ObjectId.GenerateNewId(), P = new P { X = 1, Y = 2 } }; collection.Insert(c); Assert.AreEqual(1, collection.Count()); var r = collection.FindOne(); Assert.AreEqual(2, r.ElementCount); Assert.AreEqual(2, r["P"].AsBsonDocument.ElementCount); Assert.AreEqual(c.Id, r["_id"].AsObjectId); Assert.AreEqual(c.P.X, r["P"].AsBsonDocument["X"].AsInt32); Assert.AreEqual(c.P.Y, r["P"].AsBsonDocument["Y"].AsInt32); }
private string CheckUserExists(string userName, MongoCollection<UserLegitimation> users, out string statusMessage) { statusMessage = null; string userID = null; try { if (users.Count() > 0) { var userQuery = Query.EQ("userName", userName); var existedUser = users.FindOne(userQuery); if (existedUser != null) userID = (existedUser as UserLegitimation).userID; } } catch (Exception e) { userID = null; statusMessage = "An exception has occured in CheckUserExists method. " + e.Message; } return userID; }
/// <summary> /// Get Entity List /// </summary> /// <param name="query">query</param> /// <returns></returns> public long GetCount <T>(IMongoQuery query) { MongoCollection <T> coll = MongoPooledConnection.ReadDatabase.GetCollection <T>(typeof(T).Name); return(query == null?coll.Count() : coll.Count(query)); }
public bool DoesCounterCollectionHaveDocuments(MongoCollection<BsonDocument> counterCollection) { long count = counterCollection.Count(); return count > 0; }
public long CountAllAccountsWithThisUsername(string username) { return(accountsCollection.Count(Query <Account> .EQ(a => a.Username, username))); }
public static long Count(Expression <Func <T, bool> > sel) => MongoCollection.Count(sel);
public override int GetNumberOfInactiveProfiles(ProfileAuthenticationOption authenticationOption, DateTime userInactiveSinceDate) { var query = GetQuery(authenticationOption, null, userInactiveSinceDate); return((int)mongoCollection.Count(query)); }
public int Count(string name) { return(Convert.ToInt32(_collection.Count(Query <MongoDbSslData <object> > .EQ(x => x.Name, name)))); }
/// <summary> /// 获得件数 /// </summary> /// <param name="CollectionName"></param> /// <returns></returns> public static int GetCollectionRecordCount(string CollectionName) { MongoCollection TargetCollection = innerDatabase.GetCollection(CollectionName); return((int)TargetCollection.Count()); }
public void GetByBadQuery() { queue.Send(new BsonDocument { { "key1", 0 }, { "key2", true } }); var message = queue.Get(new QueryDocument { { "key1", 0 }, { "key2", false } }, TimeSpan.MaxValue, TimeSpan.Zero); Assert.IsNull(message); Assert.AreEqual(1, collection.Count()); }
/// <summary> /// Performs the query against the database /// </summary> /// <typeparam retval="T"></typeparam> /// <returns></returns> public object Execute <T>() { // This is the actual Query mechanism... IMongoCollection <T> collection = new MongoCollection <T>(_translationResults.CollectionName, _db, _db.CurrentConnection); object result; switch (_translationResults.MethodCall) { case "Any": result = collection.Count(_translationResults.Where) > 0; break; case "Count": result = collection.Count(_translationResults.Where); break; case "Sum": result = ExecuteMapReduce <double>(_translationResults.TypeName, BuildSumMapReduce()); break; case "Average": result = ExecuteMapReduce <double>(_translationResults.TypeName, BuildAverageMapReduce()); break; case "Min": result = ExecuteMapReduce <double>(_translationResults.TypeName, BuildMinMapReduce()); break; case "Max": result = ExecuteMapReduce <double>(_translationResults.TypeName, BuildMaxMapReduce()); break; default: _translationResults.Take = IsSingleResultMethod(_translationResults.MethodCall) ? 1 : _translationResults.Take; _translationResults.Sort.ReverseKitchen(); if (_translationResults.Select == null) { result = collection.Find(_translationResults.Where, _translationResults.Sort, _translationResults.Take, _translationResults.Skip, collection.FullyQualifiedName); switch (_translationResults.MethodCall) { case "SingleOrDefault": result = ((IEnumerable <T>)result).SingleOrDefault(); break; case "Single": result = ((IEnumerable <T>)result).Single(); break; case "FirstOrDefault": result = ((IEnumerable <T>)result).FirstOrDefault(); break; case "First": result = ((IEnumerable <T>)result).First(); break; } } else { Type t = collection.GetType(); MethodInfo mi = t.GetMethod("FindFieldSelection", BindingFlags.Instance | BindingFlags.NonPublic); var sortType = _translationResults.Sort ?? new Object(); Type[] argTypes = { typeof(Expando), sortType.GetType(), _translationResults.Select.Body.Type }; MethodInfo method = mi.MakeGenericMethod(argTypes); result = method.Invoke(collection, new object[] { _translationResults.Where, _translationResults.Sort, _translationResults.Take, _translationResults.Skip, collection.FullyQualifiedName, _translationResults.Select }); switch (_translationResults.MethodCall) { case "SingleOrDefault": result = ((IEnumerable)result).OfType <Object>().SingleOrDefault(); break; case "Single": result = ((IEnumerable)result).OfType <Object>().Single(); break; case "FirstOrDefault": result = ((IEnumerable)result).OfType <Object>().FirstOrDefault(); break; case "First": result = ((IEnumerable)result).OfType <Object>().First(); break; } } break; } return(result); }
public void Dowith() { MongoClient client = new MongoClient("mongodb://localhost:27017"); MongoServer server = client.GetServer(); MongoDatabase database = server.GetDatabase("finance"); MongoCollection <BsonDocument> collection = database.GetCollection <BsonDocument>("UpLimitAnalysis"); BsonElement[] eleArray = new BsonElement[3]; BsonDocument temp = new BsonDocument(new BsonElement[] { new BsonElement("$gte", beginDate.ToString("yyyy-MM-dd")), new BsonElement("$lt", endDate.ToString("yyyy-MM-dd")) }); eleArray[0] = new BsonElement("date", temp); QueryDocument query; if (this.factor.Type == ConditionType.Field) { this.factor.Val = this.factor.MinVal; do { eleArray[1] = this.factor.ParseField(); eleArray[2] = null; query = new QueryDocument(eleArray); long c1 = collection.Count(query); eleArray[2] = this.result.Parse(); query = new QueryDocument(eleArray); long c2 = collection.Count(query); Console.WriteLine("Factor[{0}],Resule[All],Count={1}", this.factor.ToString(), c1); Console.WriteLine("Factor[{0}],Resule[{1}],Count={2}", this.factor.ToString(), this.result.ToString(), c2); if (c1 <= 0) { break; } Console.WriteLine("Rate={0}", (double)c2 / c1); this.factor.Val += this.factor.Step; }while(this.factor.Val <= this.factor.MaxVal); } else if (this.factor.Type == ConditionType.Where) { eleArray[1] = this.factor.ParseWhere(); eleArray[2] = null; query = new QueryDocument(eleArray); long c1 = collection.Count(query); if (this.result.Type == ConditionType.Where) //由于不能同时有两个$where查询子句 { string oldExp = this.factor.WhereExp; this.factor.WhereExp = this.factor.WhereExp + " && " + this.result.WhereExp; eleArray[1] = this.factor.ParseWhere(); this.factor.WhereExp = oldExp; } else { eleArray[2] = this.result.Parse(); } query = new QueryDocument(eleArray); long c2 = collection.Count(query); Console.WriteLine("Factor[{0}],Result[All],Count={1}", this.factor.ToString(), c1); Console.WriteLine("Factor[{0}],Result[{1}],Count={2}", this.factor.ToString(), this.result.ToString(), c2); Console.WriteLine("Rate={0}", (double)c2 / c1); } }
/// <summary> /// For the provided collection, will attempt to determine the name and type of each column in the collection. /// Adds the columns to both the default and error outputs. /// </summary> /// <param name="collectionName">The name of the mongo db collection</param> private void CreateColumnsFromMongoDb(string collectionName) { if (database == null) { AcquireConnections(null); } MongoCollection <BsonDocument> collection = database.GetCollection(collectionName); if (collection.Count() == 0) { throw new Exception(collectionName + " collection has no records"); } // Remove the existing columns from the output in order to prevent us from adding duplicate columns foreach (IDTSOutput100 output in ComponentMetaData.OutputCollection) { // We can't simply call RemoveAll on the error output column collection, as there // are two columns (ErrorColumn and ErrorCode) that we cannot remove as it throws an exception if we try if (output.IsErrorOut) { List <IDTSOutputColumn100> columns = new List <IDTSOutputColumn100>(); for (int i = 0; i < output.OutputColumnCollection.Count; i++) { columns.Add(output.OutputColumnCollection[i]); } string[] errorColumns = new string[] { "ErrorColumn", "ErrorCode" }; IEnumerable <int> columnIdsToRemove = columns.Where(column => !errorColumns.Contains(column.Name)).Select(column => column.ID); foreach (int columnIdToRemove in columnIdsToRemove) { output.OutputColumnCollection.RemoveObjectByID(columnIdToRemove); } } else { output.OutputColumnCollection.RemoveAll(); output.ExternalMetadataColumnCollection.RemoveAll(); } } int sampleSize = ComponentMetaData.CustomPropertyCollection[SAMPLE_SIZE_PROP_NAME].Value; int sampleOffset = ComponentMetaData.CustomPropertyCollection[SAMPLE_OFFSET_PROP_NAME].Value; // Get a sample of documents to increase the likelihood that all possible columns are found. // Offsetting the sample allows the user to move the sample window. var documents = collection .FindAll() .SetSkip(sampleOffset) .SetLimit(sampleSize); // Collect the distinct column names var elements = documents.SelectMany(document => document.Select(element => element.Name)).Distinct(); // For each data column, create an output column and an external metadata column. foreach (var element in elements) { // Try to find a document that has a [non null] value for the particular column. BsonDocument documentWithNonNullElementValue = collection.FindOne(Query.NE(element, BsonNull.Value)); // If the column is not populated in any document of the collection, don't output the column. // Without a value, we can't determine the data type of the column. if (documentWithNonNullElementValue == null) { continue; } BsonElement bsonElement = documentWithNonNullElementValue.GetElement(element); foreach (IDTSOutput100 output in ComponentMetaData.OutputCollection) { IDTSOutputColumn100 outColumn = BuildOutputColumn(output, bsonElement); IDTSExternalMetadataColumn100 externalColumn = BuildExternalMetadataColumn(output.ExternalMetadataColumnCollection, outColumn); // Map the external column to the output column. outColumn.ExternalMetadataColumnID = externalColumn.ID; } } }
/// <summary> /// Gets all Users /// </summary> /// <param name="registrationFromUtc">User registration from; null to load all users</param> /// <param name="registrationToUtc">User registration to; null to load all users</param> /// <param name="userRoleIds">A list of user role identifiers to filter by (at least one match); pass null or empty list in order to load all users;</param> /// <param name="email">Email; null to load all users</param> /// <param name="username">Username; null to load all users</param> /// <param name="firstName">First name; null to load all users</param> /// <param name="lastName">Last name; null to load all users</param> /// <param name="pageIndex">Page index</param> /// <param name="pageSize">Page size</param> /// <param name="showDeleted">Show the deleted users</param> /// <returns>User collection</returns> /// <remarks></remarks> public virtual IPagedList <User> GetAllUsers(DateTime?registrationFromUtc = null, DateTime?registrationToUtc = null, ObjectId[] userRoleIds = null, string email = null, string username = null, bool showDeleted = false, string firstName = null, string lastName = null, int pageIndex = 0, int pageSize = int.MaxValue) { var filters = new List <IMongoQuery>(); if (!showDeleted) { filters.Add(Query <User> .EQ(x => x.Deleted, false)); } if (!string.IsNullOrEmpty(email)) { var emailRegex = new Regex(email, RegexOptions.IgnoreCase); filters.Add(Query <User> .EQ(x => x.Email, BsonRegularExpression.Create(emailRegex))); } if (!string.IsNullOrEmpty(username)) { var usernameRegex = new Regex(username, RegexOptions.IgnoreCase); filters.Add(Query <User> .EQ(x => x.Username, BsonRegularExpression.Create(usernameRegex))); } if (!string.IsNullOrEmpty(firstName)) { var firstNameRegex = new Regex(firstName, RegexOptions.IgnoreCase); filters.Add(Query <User> .EQ(x => x.FirstName, BsonRegularExpression.Create(firstNameRegex))); } if (!string.IsNullOrEmpty(lastName)) { var lastNameRegex = new Regex(lastName, RegexOptions.IgnoreCase); filters.Add(Query <User> .EQ(x => x.LastName, BsonRegularExpression.Create(lastNameRegex))); } if (registrationFromUtc.HasValue) { filters.Add(Query <User> .GTE(x => x.CreatedOnUtc, registrationFromUtc.Value)); } if (registrationToUtc.HasValue) { filters.Add(Query <User> .LTE(x => x.CreatedOnUtc, registrationToUtc.Value)); } if (userRoleIds != null && userRoleIds.Length > 0) { // TODO: Optimize var validUsers = _userRoleMapCollection.Find(Query <UserUserRoleMap> .In(x => x.UserRoleId, userRoleIds)).SetFields(Fields <UserUserRoleMap> .Include(x => x.UserId)).Select(x => x.UserId).Distinct(); filters.Add(Query <User> .In(x => x.Id, validUsers)); } var query = filters.Any() ? Query.And(filters) : null; var total = query != null?_userCollection.Count(query) : _userCollection.Count(); var logs = (query != null ? _userCollection.Find(query) : _userCollection.FindAll()) .SetSkip(pageIndex * pageSize) .SetLimit(pageSize) .ToList(); return(new PagedList <User>(logs, pageIndex, pageSize, (int)total)); }
// // GetProfileInfo // Retrieves a count of profiles and creates a // ProfileInfoCollection from the profile data in the // database. Called by GetAllProfiles, GetAllInactiveProfiles, // FindProfilesByUserName, FindInactiveProfilesByUserName, // and GetNumberOfInactiveProfiles. // Specifying a pageIndex of 0 retrieves a count of the results only. // /// <summary> /// Gets the profile info. /// </summary> /// <param name="authenticationOption">The authentication option.</param> /// <param name="usernameToMatch">The username to match.</param> /// <param name="userInactiveSinceDate">The user inactive since date.</param> /// <param name="pageIndex">Index of the page.</param> /// <param name="pageSize">Size of the page.</param> /// <param name="totalRecords">The total records.</param> /// <returns></returns> private ProfileInfoCollection GetProfileInfo( ProfileAuthenticationOption authenticationOption, string usernameToMatch, object userInactiveSinceDate, int pageIndex, int pageSize, out int totalRecords) { MongoServer server = MongoServer.Create(connectionString); // connect to the mongoDB url. MongoDatabase ProviderDB = server.GetDatabase(pMongoProviderDatabaseName, SafeMode.True); MongoCollection <BsonDocument> profiles = ProviderDB.GetCollection(pMongoProviderProfileCollectionName); var query = Query.EQ("ApplicationNameLowerCase", pApplicationName.ToLower()); // If searching for a user name to match, add the command text and parameters. if (!String.IsNullOrWhiteSpace(usernameToMatch)) { query = Query.And(query, Query.EQ("UsernameLowerCase", usernameToMatch.Trim().ToLower())); } // If searching for inactive profiles, // add the command text and parameters. if (userInactiveSinceDate != null) { query = Query.And(query, Query.LT("LastActivityDate", (DateTime)userInactiveSinceDate)); } // If searching for a anonymous or authenticated profiles, // add the command text and parameters. switch (authenticationOption) { case ProfileAuthenticationOption.Anonymous: query = Query.And(query, Query.EQ("IsAnonymous", true)); break; case ProfileAuthenticationOption.Authenticated: query = Query.And(query, Query.EQ("IsAnonymous", false)); break; default: break; } ProfileInfoCollection profilesCollection = new ProfileInfoCollection(); try { // Get the profile count. totalRecords = (int)profiles.Count(query); // No profiles found. if (totalRecords == 0) { return(profilesCollection); } // Count profiles only. if (pageSize == 0) { return(profilesCollection); } var cursor = profiles.Find(query); cursor.SetFields(new string[] { "Username", "LastActivityDate", "LastUpdatedDate", "IsAnonymous" }); cursor.Skip = Math.Max(0, pageSize * (pageIndex - 1)); cursor.Limit = pageSize; foreach (var profile in cursor) { ProfileInfo p = GetProfileInfoFromReader(profile); profilesCollection.Add(p); } } catch (ApplicationException e) { if (WriteExceptionsToEventLog) { WriteToEventLog(e, "GetProfileInfo"); throw new ProviderException(exceptionMessage, e); } else { throw e; } } return(profilesCollection); }
public long GetCountReview() { return(digikalaReview.Count()); }
/// <summary> /// To get the count of documents. /// </summary> /// <typeparam name="T">The type of the collection.</typeparam> /// <param name="collectionName">The collection name.</param> /// <param name="query">The MongoQuery to get the count.</param> /// <returns>count as integer value.</returns> public int GetCountByQuery <T>(string collectionName, MongoDB.Driver.IMongoQuery query) { MongoCollection collection = this.GetMongoDBCollection <T>(collectionName); return(int.Parse(collection.Count(query).ToString())); }
public static long Count() => MongoCollection.Count(Builders <T> .Filter.Empty);
public long Count() { return(_collection.Count()); }
public int numDocumentos() { return((int)coll.Count()); }
/// <summary> /// Returns a count of all tags in system. /// </summary> /// <returns></returns> public int GetTagCount() { return((int)MongoCollection.Count()); }
/// <summary> /// Counts the number of documents in this collection. /// </summary> /// <returns>The number of documents in this collection.</returns> public virtual long Count() { return(_collection.Count()); }
public static long Count <T>(this MongoCollection <T> collection, IMongoQuery query) { return(collection.Count(query)); }
/// <summary> /// /// </summary> /// <returns></returns> public long GetCount() { return(MongoCollection.Count()); }
public static bool IsExist(this MongoCollection collection, IMongoQuery predicate) { return(collection.Count(predicate) > 0); }
public long Count() { return(_this.Count()); }
/// <summary> /// Counts the number of documents in this collection. /// </summary> /// <typeparam name="T">The default document type for this collection.</typeparam> /// <param name="collection">An instance of MongoCollection.</param> /// <returns>The number of documents in this collection.</returns> public virtual long Count <T>(MongoCollection <T> collection) { lock (_lockObject) return(collection.Count()); }
public int GetQuestionCount() { return((int)_collection.Count()); }
public bool HasStoredLevelInfo() { GuardForInitialized(); return(elevatorCollection.Count() > 0); }
public void TestBsonDocumentNoId() { _collection.RemoveAll(); var document = new BsonDocument { { "A", 1 } }; _collection.Save(document); Assert.AreEqual(2, document.ElementCount); Assert.AreEqual("_id", document.GetElement(0).Name); Assert.IsInstanceOf <BsonObjectId>(document["_id"]); Assert.AreNotEqual(ObjectId.Empty, document["_id"].AsObjectId); Assert.AreEqual(1, _collection.Count()); var id = document["_id"].AsObjectId; document["A"] = 2; _collection.Save(document); Assert.AreEqual(id, document["_id"].AsObjectId); Assert.AreEqual(1, _collection.Count()); document = _collection.FindOneAs <BsonDocument>(); Assert.AreEqual(2, document.ElementCount); Assert.AreEqual(id, document["_id"].AsObjectId); Assert.AreEqual(2, document["A"].AsInt32); }
public static void Connect() { Console.WriteLine("Mongo DB Test Application"); Console.WriteLine("===================================================="); Console.WriteLine("Started By:Kailash Chandra Behera"); Console.WriteLine("Started On: 14 July 2014"); Console.WriteLine("Configuration Setting: 172.16.1.24:27017"); Console.WriteLine("===================================================="); Console.WriteLine("Initializaing connection"); string connectionString = "mongodb://localhost:27017"; Console.WriteLine("Creating Client.........."); MongoClient client = null; try { client = new MongoClient(connectionString); Console.WriteLine("Client Created Successfuly........"); Console.WriteLine("Client: " + client.ToString()); } catch (Exception ex) { Console.WriteLine("Filed to Create Client......."); Console.WriteLine(ex.Message); } Console.WriteLine("Initianting Mongo Db Server......."); MongoServer server = null; try { Console.WriteLine("Getting Servicer object......"); server = client.GetServer(); Console.WriteLine("Server object created Successfully...."); Console.WriteLine("Server :" + server.ToString()); } catch (Exception ex) { Console.WriteLine("Filed to getting Server Details"); Console.WriteLine(ex.Message); } Console.WriteLine("Initianting Mongo Databaser........."); MongoDatabase database = null; try { Console.WriteLine("Getting reference of database......."); database = server.GetDatabase("kara_db"); Console.WriteLine("Database Name : " + database.Name); } catch (Exception ex) { Console.WriteLine("Failed to Get reference of Database"); Console.WriteLine("Error :" + ex.Message); } try { Console.WriteLine("Deleteing Collection Symbol"); database.DropCollection("Symbol"); } catch (Exception ex) { Console.WriteLine("Failed to delete collection from Database"); Console.WriteLine("Error :" + ex.Message); } Console.WriteLine("Getting Collections from database Database......."); MongoCollection symbolcollection = null; try { symbolcollection = database.GetCollection <Symbol>("Symbols"); Console.WriteLine(symbolcollection.Count().ToString()); } catch (Exception ex) { Console.WriteLine("Failed to Get collection from Database"); Console.WriteLine("Error :" + ex.Message); } ObjectId id = new ObjectId(); Console.WriteLine("Inserting document to collection............"); try { Symbol symbol = new Symbol(); symbol.Name = "Star"; symbolcollection.Insert(symbol); id = symbol.ID; Console.WriteLine(symbolcollection.Count().ToString()); } catch (Exception ex) { Console.WriteLine("Failed to insert into collection of Database " + database.Name); Console.WriteLine("Error :" + ex.Message); } try { //Console.WriteLine("Preparing Query Document............"); //List<Symbol> query = symbolcollection.AsQueryable<Entity>().Where<Entity>(sb => sb.Name == "Kailash").ToList(); //Symbol symbol = symbolcollection.AsQueryable<Entity>().Where<Entity>(sb => sb.ID == id).ToList(); } catch (Exception ex) { Console.WriteLine("Failed to query from collection"); Console.WriteLine("Exception :" + ex.Message); } }
private string CheckLocExists(double latitude, double longitude, MongoCollection<Location> locations, out string statusMessage) { statusMessage = null; string locationID = null; try { if (locations.Count() > 0) { var locationQuery = Query.And(Query.EQ("longitude", longitude), Query.EQ("latitude", latitude)); var existedLocation = locations.FindOne(locationQuery); if (existedLocation != null) locationID = (existedLocation as Location).locationID; //File.WriteAllText(@"C:\locations.txt", "(current locationQuery) = " + locationQuery.ToJson() + " (current existedLocation) = " + existedLocation.ToJson() + " locationID = " + locationID + " " + DateTime.Now); } } catch (Exception e) { locationID = null; statusMessage = "An exception has occured in CheckLocExists method. " + e.Message; } return locationID; }
/// <summary> /// Install permissions /// </summary> /// <param name="permissionProvider">Permission provider</param> /// <param name="reInstall">If true and the provider has already been installed, it will re add the permissions with the associated default permissions. /// If not, nothing will be done with the permissions.</param> /// <remarks></remarks> public virtual void InstallPermissions(IPermissionProvider permissionProvider, bool reInstall = false) { var providerName = permissionProvider.GetType().Name; if (reInstall) { _permissionsInstalledCollection.Remove(Query <PermissionInstalled> .EQ(x => x.Name, providerName)); } else if (_permissionsInstalledCollection.Count(Query <PermissionInstalled> .EQ(x => x.Name, providerName)) == 1) { return; } _permissionsInstalledCollection.Insert(new PermissionInstalled { Name = providerName }); foreach (var permission in permissionProvider.GetPermissions()) { var existing = _permissionPecordCollection.FindOne(Query <PermissionRecord> .EQ(x => x.SystemName, permission.SystemName)) ?? new PermissionRecord(); existing.Category = permission.Category; existing.Name = permission.Name; existing.SystemName = permission.SystemName; if (existing.Id == ObjectId.Empty) { _permissionPecordCollection.Insert(existing); } else { _permissionPecordCollection.Update(Query <PermissionRecord> .EQ(x => x.Id, existing.Id), Update <PermissionRecord> .Replace(existing)); } } foreach (var defaultPermission in permissionProvider.GetDefaultPermissions()) { var role = _userRoleCollection.FindOne(Query <UserRole> .EQ(x => x.SystemName, defaultPermission.UserRoleSystemName)); if (role == null) { role = new UserRole { Active = true, IsSystemRole = false, Name = defaultPermission.UserRoleSystemName, SystemName = defaultPermission.UserRoleSystemName }; _userRoleCollection.Insert(role); } foreach (var defaultPermissionRecord in defaultPermission.PermissionRecords) { var dbPermissionRecord = _permissionPecordCollection.FindOne(Query <PermissionRecord> .EQ(x => x.SystemName, defaultPermissionRecord.SystemName)); if (dbPermissionRecord == null) { throw new InvalidOperationException("The permission provider " + providerName + " is trying to install a default permission for permission " + defaultPermissionRecord.SystemName + " but it isn't provided via GetDefaultPermissions or another IPermissionProvider"); } var query = Query.And(Query <RolePermissionMap> .EQ(x => x.PermissionRecordId, dbPermissionRecord.Id), Query <RolePermissionMap> .EQ(x => x.UserRoleId, role.Id)); var existing = _rolePermissionMapCollection.FindOne(query); if (existing != null) { continue; } _rolePermissionMapCollection.Insert(new RolePermissionMap { PermissionRecordId = dbPermissionRecord.Id, UserRoleId = role.Id }); } } }