public void TestArrayInsert() { IMongoCollection inserts = db["tests"]["inserts"]; Document indoc1 = new Document(); indoc1["song"] = "The Axe"; indoc1["artist"] = "Tinsley Ellis"; indoc1["year"] = 2006; Document indoc2 = new Document(); indoc2["song"] = "The Axe2"; indoc2["artist"] = "Tinsley Ellis2"; indoc2["year"] = 2008; inserts.Insert(new Document[] { indoc1, indoc2 }); Document result = inserts.FindOne(new Document().Append("song", "The Axe")); Assert.IsNotNull(result); Assert.AreEqual(2006, result["year"]); result = inserts.FindOne(new Document().Append("song", "The Axe2")); Assert.IsNotNull(result); Assert.AreEqual(2008, result["year"]); }
public void TestUpdateUpsertExisting() { IMongoCollection updates = db["tests"]["updates"]; Document doc = new Document(); doc["First"] = "Mtt"; doc["Last"] = "Brewer"; updates.Insert(doc); Document selector = new Document().Append("Last", "Brewer"); doc = updates.FindOne(selector); Assert.IsNotNull(doc); Assert.AreEqual("Mtt", doc["First"]); Assert.IsNotNull(doc["_id"]); doc["First"] = "Matt"; updates.Update(doc); Document result = updates.FindOne(selector); Assert.IsNotNull(result); Assert.AreEqual("Matt", result["First"]); }
/// <summary> /// Stores a function in the database. /// </summary> /// <param name="item">The object to add to the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param> /// <exception cref="T:System.NotSupportedException"> /// The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only. /// </exception> public void Add(Document item) { if (_collection.FindOne(new Document("_id", item.Id)) != null) { throw new ArgumentException(String.Format("Function {0} already exists in the database.", item.Id)); } _collection.Insert(item); }
public void FindOne_WithAny() { var person = personCollection.FindOne(e => e.Aliases.Any(a => a == "Blub")); Assert.IsNotNull(person); Assert.AreEqual("Bob", person.FirstName); }
// The timer that publishes measurements coming from the MongoDB database. private void Timer_Elapsed(object sender, ElapsedEventArgs e) { try { long nowTicks = DateTime.UtcNow.Ticks; ICursor <MeasurementWrapper> wrappers; List <IMeasurement> measurements; MeasurementWrapper foundWrapper; // Find the first measurements whose timestamp is larger than the last-used timestamp. foundWrapper = m_measurementCollection.FindOne(new { Timestamp = Op.GreaterThan(m_lastTimestamp) }); // If no measurement was found, find the first measurement. if (foundWrapper == null) { foundWrapper = m_measurementCollection.FindOne(new Document()); } // Find all measurements with the timestamp of the measurement that was found. wrappers = m_measurementCollection.Find(new { foundWrapper.Timestamp }); measurements = wrappers.Documents.Select(wrapper => wrapper.GetMeasurement()).ToList(); // Simulate real-time. if (m_simulateRealTime) { measurements.ForEach(measurement => measurement.Timestamp = nowTicks); } // Set the last-used timestamp to the new value and publish the measurements. m_lastTimestamp = foundWrapper.Timestamp; OnNewMeasurements(measurements); } catch { // Stop the timer to prevent flooding // the user with error messages. m_timer.Stop(); throw; } }
public void Save_Inserts_Or_Updates() { var c = new CheeseClubContact(); c.Id = ObjectId.NewObjectId(); _collection.Save(c); var a = _collection.FindOne(new { c.Id }); //prove it was inserted. Assert.Equal(c.Id, a.Id); c.Name = "hello"; _collection.Save(c); var b = _collection.FindOne(new { c.Id }); //prove that it was updated. Assert.Equal(c.Name, b.Name); }
public void FindOneReturnsSomething() { _coll.Insert(new TestClass { ADouble = 1d }); var found = _coll.FindOne(new { ADouble = 1d }); Assert.NotNull(found); }
public void Run() { var category = categories.FindOne(new Document { { "name", "Bluez" } }); Console.WriteLine("The id findOne" + category["_id"]); var selector = new Document { { "_id", category["_id"] } }; category["name"] = "Bluess"; //The following will do the same thing. categories.Save(category); Console.WriteLine("Category after one update " + categories.FindOne(selector)); category["name"] = "Blues"; categories.Update(category, selector); Console.WriteLine("Category after two updates " + categories.FindOne(selector)); //Find it by _id that has been converted to a string now. var id = (category["_id"]).ToString(); Console.WriteLine("Found by string id converted back to Oid"); Console.WriteLine(categories.FindOne(new Document { { "_id", id.ToOid() } })); //Find(new Document()) is equivalent to FindAll(); //Specifying the cursor in a using block will close it on the server if we decide not //to iterate through the whole thing. using (var all = categories.Find(new Document())) { foreach (var doc in all.Documents) { Console.WriteLine(doc.ToString()); } } mongo.Disconnect(); }
public void TestDelete() { IMongoCollection deletes = db["tests"]["deletes"]; Document doc = new Document(); doc["y"] = 1; doc["x"] = 2; deletes.Insert(doc); Document selector = new Document().Append("x", 2); Document result = deletes.FindOne(selector); Assert.IsNotNull(result); Assert.AreEqual(1, result["y"]); deletes.Delete(selector); result = deletes.FindOne(selector); Assert.IsNull(result, "Shouldn't have been able to find a document that was deleted"); }
public void TestMongoInsert() { MongoEntity entity = new MongoEntity { 备注 = "insert1" }; manager.Insert(new MongoEntity[] { entity }); var query = new Expando(); query["_id"] = entity.Id; Assert.IsNotNull(manager.FindOne(query)); manager.Delete(query); }
public void TestPoundSymbolInsert() { IMongoCollection inserts = db["tests"]["inserts"]; Document indoc = new Document().Append("x", "1234" + pound + "56").Append("y", 1);; inserts.Insert(indoc); Document result = inserts.FindOne(new Document().Append("x", "1234" + pound + "56")); Assert.IsNotNull(result); Assert.AreEqual(1, result["y"]); }
/// <summary> /// 获取一条数据 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="collectionName"></param> /// <param name="query"></param> /// <returns></returns> public static T GetOne <T>(string collectionName, Document query) where T : class { T result = default(T); using (Mongo mongo = new Mongo(connectionString)) { mongo.Connect(); IMongoDatabase friends = mongo.GetDatabase(database); IMongoCollection <T> collection = friends.GetCollection <T>(collectionName); result = collection.FindOne(query); mongo.Disconnect(); } return(result); }
public void TestAuthenticatedInsert() { bool ok = Authenticate(); IMongoCollection tests = db["inserts"]; if (ok) { tests.Insert(new Document().Append("value", 34)); } Document valA = tests.FindOne(new Document().Append("value", 34)); Assert.AreEqual(34, valA["value"]); db.Logout(); }
public void TestReallySimpleInsert() { IMongoCollection inserts = db["tests"]["inserts"]; Document indoc = new Document(); indoc["y"] = 1; indoc["x"] = 2; inserts.Insert(indoc); Document result = inserts.FindOne(new Document().Append("x", 2)); Assert.IsNotNull(result); Assert.AreEqual(1, result["y"]); }
public void TestUnauthenticatedInsert() { try{ db.Logout(); }catch (MongoException) { //We don't care. Just wanted to make sure we weren't logged in } IMongoCollection tests = db["inserts"]; tests.Insert(new Document().Append("value", 84)); Document valA = tests.FindOne(new Document().Append("value", 84)); Assert.AreNotEqual(84, valA["value"]); }
public void TestUpdateUpsertNotExisting() { IMongoCollection updates = db["tests"]["updates"]; Document doc = new Document(); doc["First"] = "Sam"; doc["Last"] = "CorderNE"; updates.Update(doc); Document selector = new Document().Append("Last", "CorderNE"); Document result = updates.FindOne(selector); Assert.IsNotNull(result); Assert.AreEqual("Sam", result["First"]); }
public void TestSimpleInsert() { IMongoCollection inserts = db["tests"]["inserts"]; Document indoc = new Document(); indoc["song"] = "Palmdale"; indoc["artist"] = "Afroman"; indoc["year"] = 1999; inserts.Insert(indoc); Document result = inserts.FindOne(new Document().Append("song", "Palmdale")); Assert.IsNotNull(result); Assert.AreEqual(1999, result["year"]); }
public static List <VEHICLE> GetVehiclesByMarketMakeModel(string market, string make, string model, string pricerange) { List <VEHICLE> retval = null; using (Mongo mongo = new Mongo(config.BuildConfiguration())) { mongo.Connect(); var db = mongo.GetDatabase(VehicleRecords.VEHICLE_DB.DataBaseName); IMongoCollection <Document> collPriceRange = db.GetCollection <Document>(PRICERANGE.TableName); Document qPriceRange = new Document(); qPriceRange["VALUENAME"] = pricerange; Document docPriceRange = collPriceRange.FindOne(qPriceRange); PRICERANGE pr = PRICERANGE.GetPRICERANGEFromDocument(docPriceRange); IMongoCollection <Document> collVehicles = db.GetCollection <Document>(VEHICLE.TableName); Document qVehicles = new Document(); qVehicles["MARKET"] = market; if (make.Length > 0 && make != "All") { qVehicles["MAKE"] = make; } if (model.Length > 0 && model != "All") { qVehicles["MODEL"] = model; } qVehicles["STILL_FOR_SALE"] = "YES"; string where = $"(this.CURRENT_PRICE >= {pr.LOWBOUND} && this.CURRENT_PRICE <= {pr.HIGHBOUND})"; qVehicles.Add("$where", new Code(where)); VEHICLE[] foundvehicles = VEHICLE.GetVEHICLEsFromQueryDocument(collVehicles, qVehicles); if (foundvehicles != null && foundvehicles.Count <VEHICLE>() > 0) { retval = foundvehicles.ToList <VEHICLE>(); } mongo.Disconnect(); } return(retval); }
public UserFavorite(Database db, string username) { DB = db; UserFavoriteCollection = DB["UserFavorite"]; // initial from db var spec = new Document() { { "username", username } }; InternalDocument = UserFavoriteCollection.FindOne(spec); if (InternalDocument == null) { InternalDocument = new Document { { "username", username } }; DB["UserFavorite"].Insert(InternalDocument); } }
public static bool UpdateDocumentFromMEMBER(IMongoCollection <Document> coll, VEHICLE val) { bool ret = true; Document doc = new Document(); var q = new Document(); q["_id"] = val._id; doc = coll.FindOne(q); if (doc.Count == 0) { return(false); } doc["VIN"] = val.VIN; doc["YEAR"] = val.YEAR; doc["MAKE"] = val.MAKE; doc["MODEL"] = val.MODEL; doc["TRIM"] = val.TRIM; doc["BODY_STYLE"] = val.BODY_STYLE; doc["ENGINE"] = val.ENGINE; doc["TRANSMISSION"] = val.TRANSMISSION; doc["DRIVE_TRAIN"] = val.DRIVE_TRAIN; doc["WHEEL_SIZE"] = val.WHEEL_SIZE; doc["COLOR_EXTERIOR"] = val.COLOR_EXTERIOR; doc["COLOR_INTERIOR"] = val.COLOR_INTERIOR; doc["MARKET"] = val.MARKET; doc["IMAGEIDCSV"] = val.IMAGEIDCSV; doc["MILEAGE"] = val.MILEAGE; doc["CURRENT_PRICE"] = val.CURRENT_PRICE; doc["VEHICLE_HISTORY"] = val.VEHICLE_HISTORY; doc["STILL_FOR_SALE"] = val.STILL_FOR_SALE; doc["STOCK_NUMBER"] = val.STOCK_NUMBER; doc["DEALERSHIP_NAME"] = val.DEALERSHIP_NAME; doc["MODEL_CODE"] = val.MODEL_CODE; doc["CARFAX_URL"] = val.CARFAX_URL; doc["DEALER_DETAIL_URL"] = val.DEALER_DETAIL_URL; doc["DATE_LAST_SEEN"] = val.DATE_LAST_SEEN; coll.Save(doc); return(ret); }
public static bool UpdateDocumentFromMEMBER(IMongoCollection <Document> coll, DEALERSHIP val) { bool ret = true; Document doc = new Document(); var q = new Document(); q["_id"] = val._id; doc = coll.FindOne(q); if (doc.Count == 0) { return(false); } doc["DEALER_NAME"] = val.DEALER_NAME; doc["DEALER_URL"] = val.DEALER_URL; doc["PARSER_TYPE"] = val.PARSER_TYPE; doc["MARKET_AREA_NAME"] = val.MARKET_AREA_NAME; coll.Save(doc); return(ret); }
/// <summary> /// 更新或增加一个新文档 /// </summary> /// <param name="entity"></param> /// <param name="tableName">表名 </param> /// <param name="keyName"> </param> /// <param name="keyvalue"> </param> public override void SaveOrUpdateEntity( IFreeDocument entity, string tableName, IDictionary <string, object> keys = null, EntityExecuteType executeType = EntityExecuteType.InsertOrUpdate) { if (IsUseable == false) { return; } IMongoCollection <Document> collection = DB.GetCollection <Document>(tableName); if (executeType == EntityExecuteType.OnlyInsert) { InsertEntity(entity, collection, tableName); return; } var query = new Document(keys); Document document = collection.FindOne(query); if (executeType == EntityExecuteType.Delete) { collection.Remove(query); return; } if (document != null) { UpdateDocument(entity, document); if (executeType == EntityExecuteType.InsertOrUpdate || executeType == EntityExecuteType.OnlyUpdate) { collection.Save(document); } } else { if (executeType == EntityExecuteType.InsertOrUpdate || executeType == EntityExecuteType.OnlyInsert) { InsertEntity(entity, collection, tableName); } } }
public static PRICERANGE GetPriceRange(string ValueName) { PRICERANGE retval = null; using (Mongo mongo = new Mongo(config.BuildConfiguration())) { mongo.Connect(); var db = mongo.GetDatabase(VehicleRecords.VEHICLE_DB.DataBaseName); IMongoCollection <Document> collVehicles = db.GetCollection <Document>(PRICERANGE.TableName); var qPR = new Document(); qPR["VALUENAME"] = ValueName; Document resultsdoc = collVehicles.FindOne(qPR); if (resultsdoc != null) { retval = PRICERANGE.GetPRICERANGEFromDocument(resultsdoc); } } return(retval); }
public static VEHICLE GetVehicleByVIN(string VIN) { VEHICLE retval = null; using (Mongo mongo = new Mongo(config.BuildConfiguration())) { mongo.Connect(); var db = mongo.GetDatabase(VehicleRecords.VEHICLE_DB.DataBaseName); IMongoCollection <Document> collVehicles = db.GetCollection <Document>(VEHICLE.TableName); var qVeh = new Document(); qVeh["VIN"] = VIN; Document resultsdoc = collVehicles.FindOne(qVeh); if (resultsdoc != null) { retval = VEHICLE.GetVEHICLEFromDocument(resultsdoc); } } return(retval); }
/// <summary> /// 创建一个自增主键索引表 /// </summary> /// <param name="tableName">表名</param> public void CreateIndexTable(string tableName) { if (IsUseable == false) { return; } IMongoCollection idManager = DB.GetCollection("ids"); Document idDoc = idManager.FindOne(new Document("Name", tableName)); if (idDoc == null) { idDoc = new Document(); idDoc["Name"] = tableName; idDoc[AutoIndexName] = 0; } else { idDoc[AutoIndexName] = 0; } idManager.Save(idDoc); }
public static bool UpdateDocumentFromMEMBER(IMongoCollection <Document> coll, PRICERANGE val) { bool ret = true; Document doc = new Document(); var q = new Document(); q["_id"] = val._id; doc = coll.FindOne(q); if (doc.Count == 0) { return(false); } doc["DISPLAYORDER"] = val.DISPLAYORDER; doc["VALUENAME"] = val.VALUENAME; doc["DISPLAYNAME"] = val.DISPLAYNAME; doc["LOWBOUND"] = val.LOWBOUND; doc["HIGHBOUND"] = val.HIGHBOUND; doc["DISPLAY_THIS_RANGE"] = val.DISPLAY_THIS_RANGE; coll.Save(doc); return(ret); }
public static bool UpdateDocumentFromMEMBER(IMongoCollection <Document> coll, IMAGE val) { bool ret = true; Document doc = new Document(); var q = new Document(); q["_id"] = val._id; doc = coll.FindOne(q); if (doc.Count == 0) { return(false); } doc["IMAGEID"] = val.ImageId; doc["CONTENTTYPE"] = val.ContentType; doc["IMAGEDATA"] = new Binary(val.ImageData); doc["IMAGENAME"] = val.ImageName; doc["TIMESSERVED"] = val.TimesServed; coll.Save(doc); return(ret); }
public void TestInsertOfArray() { OidGenerator ogen = new OidGenerator(); IMongoCollection inserts = db["tests"]["inserts"]; Document album = new Document(); album["_id"] = ogen.Generate(); album["artist"] = "Popa Chubby"; album["title"] = "Deliveries After Dark"; album["songs"] = new[] { new Document().Append("title", "Let The Music Set You Free").Append("length", "5:15").Append("_id", ogen.Generate()), new Document().Append("title", "Sally Likes to Run").Append("length", "4:06").Append("_id", ogen.Generate()), new Document().Append("title", "Deliveries After Dark").Append("length", "4:17").Append("_id", ogen.Generate()), new Document().Append("title", "Theme From The Godfather").Append("length", "3:06").Append("_id", ogen.Generate()), new Document().Append("title", "Grown Man Crying Blues").Append("length", "8:09").Append("_id", ogen.Generate()), }; inserts.Insert(album); Document result = inserts.FindOne(new Document().Append("songs.title", "Deliveries After Dark")); Assert.IsNotNull(result); Assert.AreEqual(album.ToString(), result.ToString()); }
public static IMAGE GetImage(int ImageId) { IMAGE retval = null; using (Mongo mongo = new Mongo(config.BuildConfiguration())) { mongo.Connect(); var db = mongo.GetDatabase(VehicleRecords.VEHICLE_DB.DataBaseName); IMongoCollection <Document> collImage = db.GetCollection <Document>(IMAGE.TableName); var qIM = new Document(); qIM["IMAGEID"] = ImageId; Document resultsdoc = collImage.FindOne(qIM); if (resultsdoc != null) { retval = IMAGE.GetIMAGEFromDocument(resultsdoc); IMAGE.UpdateDocumentFromMEMBER(collImage, retval); // Update "times served" counter } } return(retval); }
public override List <IFreeDocument> TryFindEntities(string tableName, IDictionary <string, object> search , Type type = null, int count = -1, DBSearchStrategy searchStrategy = DBSearchStrategy.Contains) { if (type == null) { type = typeof(FreeDocument); } if (IsUseable == false) { return(new List <IFreeDocument>()); } IMongoCollection <Document> collection = DB.GetCollection <Document>(tableName); var querydoc = new Document(); foreach (var r in search) { querydoc.Add(r.Key, r.Value); } if (count != 1) { ICursor <Document> document = collection.Find(querydoc); if (document == null) { return(new List <IFreeDocument>()); } var results = new List <IFreeDocument>(); foreach (Document item in document.Documents) { if (count > 0) { count--; } if (count == 0) { break; } var result = Activator.CreateInstance(type) as IFreeDocument; result.DictDeserialize(item); results.Add(result); } return(results); } else { var document = collection.FindOne(querydoc); if (document == null) { return(new List <IFreeDocument>()); } var results = new List <IFreeDocument>(); var result = Activator.CreateInstance(type) as IFreeDocument; result.DictDeserialize(document); results.Add(result); return(results); } }
/// <summary> /// Finds the one. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="collection">The collection.</param> /// <param name="selector">The selector.</param> /// <returns></returns> public static T FindOne <T>(this IMongoCollection <T> collection, Expression <Func <T, bool> > selector) where T : class { return(collection.FindOne(GetQuery(collection, selector))); }
/// <summary> /// Demoes Updates a single field using an atomic Increment ($inc) operator. /// </summary> /// <param name="orders">The orders.</param> private static void UpdateUsingAtomicIncrement(IMongoCollection orders) { Console.WriteLine("\n\n======= Update Document using Increment ======="); var selector = new Document { { "CustomerName", "Daffy Duck" } }; Console.WriteLine("Before Update: " + orders.FindOne(selector)); // Add 2000 to order amount on document matching selector. orders.Update( new Document {{"$inc", new Document {{"OrderAmount", 2000}} }}, selector ); Console.WriteLine("After Update: " + orders.FindOne(selector)); }
/// <summary> /// Demo of Updating a document. /// </summary> /// <param name="orders">The orders.</param> private static void UpdateDocument( IMongoCollection orders ) { Console.WriteLine( "\n\n======= Update Documents =======" ); var selector = new Document {{"CustomerName", "Daffy Duck"}}; Document docToUpdate = orders.FindOne( selector ); Console.WriteLine( "Before Update: " + docToUpdate ); // I'm in the money! docToUpdate["OrderAmount"] = 1000000.00; // Update Daffy's account before Hasaan finds him. orders.Update( docToUpdate ); Console.WriteLine( "After Update: " + orders.FindOne( selector ) ); }
/// <summary> /// Demos querying the collection. /// </summary> /// <param name="orders">The orders.</param> private static void QueryFromCollection( IMongoCollection orders ) { Console.WriteLine( "\n\n======= Query One Document =======" ); // Create a specification to query the orders collection. var spec = new Document(); spec["CustomerName"] = "Elmer Fudd"; // Run the query. Document result = orders.FindOne( spec ); Console.WriteLine( string.Format( "Found: {0}", result ) ); }