コード例 #1
0
 public override void OnInit()
 {
     mrcol = DB["mr"];
     mrcol.Insert(new Document().Append("_id", 1).Append("tags", new String[]{"dog", "cat"}));
     mrcol.Insert(new Document().Append("_id", 2).Append("tags", new String[]{"dog"}));
     mrcol.Insert(new Document().Append("_id", 3).Append("tags", new String[]{"mouse", "cat", "dog"}));
     mrcol.Insert(new Document().Append("_id", 4).Append("tags", new String[]{}));
 }
コード例 #2
0
 public override void OnInit()
 {
     _collection = DB["mr"];
     _collection.Insert(new Document().Add("_id", 1).Add("tags", new[] {"dog", "cat"}));
     _collection.Insert(new Document().Add("_id", 2).Add("tags", new[] {"dog"}));
     _collection.Insert(new Document().Add("_id", 3).Add("tags", new[] {"mouse", "cat", "dog"}));
     _collection.Insert(new Document().Add("_id", 4).Add("tags", new String[] {}));
 }
コード例 #3
0
ファイル: GeospatialTests.cs プロジェクト: hafstrom/NoRM
        public GeospatialTests()
        {
            _server = Mongo.Create("mongodb://localhost/NormTests?pooling=false");
            _collection = _server.GetCollection<GeoTestClass>("LatLngTests");

            _collection.Insert(new GeoTestClass { Location = new LatLng { Latitude = 57.1056, Longitude = 12.2508 }, Name = "Varberg"});
            _collection.Insert(new GeoTestClass { Location = new LatLng { Latitude = 57.7, Longitude = 11.9166667 }, Name = "Gothenburg" }); //  ~70km North of Varberg
            _collection.Insert(new GeoTestClass { Location = new LatLng { Latitude = 29.950975, Longitude = -90.081217 }, Name = "New Orleans Saints" });
            _collection.Insert(new GeoTestClass { Location = new LatLng { Latitude = 44.973876, Longitude = -93.258133 }, Name = "Minnesota Vikings" });
            _collection.Insert(new GeoTestClass { Location = new LatLng { Latitude = 0, Longitude = 0 }, Name = "Center of the Earth" });
            _collection.CreateGeoIndex(geo => geo.Location, "loc", true);
        }
コード例 #4
0
        public void TestSetup()
        {
            personCollection = this.DB.GetCollection<Person>("people");
            personCollection.Delete(new { }, true);
            personCollection.Insert(new Person { FirstName = "Bob", LastName = "McBob", Age = 42, Address = new Address { City = "London" }, Aliases = new[]{"Blub"} }, true);
            personCollection.Insert(new Person { FirstName = "Jane", LastName = "McJane", Age = 35, Address = new Address { City = "Paris" } }, true);
            personCollection.Insert(new Person { FirstName = "Joe", LastName = "McJoe", Age = 21, Address = new Address { City = "Chicago" } }, true);

            orgCollection = this.DB.GetCollection<Organization>("orgs");
            orgCollection.Delete(new { }, true);
            orgCollection.Insert(new Organization { Name = "The Muffler Shanty", Address = new Address { City = "London" } }, true);
        }
コード例 #5
0
ファイル: QueryTests.cs プロジェクト: gaoninggn/NoRM
 public QueryTests()
 {
     var admin = new MongoAdmin("mongodb://localhost/admin?pooling=false&strict=true");
     _server = Mongo.Create("mongodb://localhost/NormTests?pooling=false");
     _collection = _server.GetCollection<Person>("People");
     _buildInfo = admin.BuildInfo();
     //cause the collection to exist on the server by inserting, then deleting some things.
     _collection.Insert(new Person());
     _collection.Delete(new { });
 }
コード例 #6
0
 /// <summary>
 /// Stores a collection of measurements in the MongoDB database.
 /// </summary>
 /// <param name="measurements">The measurements to be stored in the MongoDB database.</param>
 protected override void ProcessMeasurements(IMeasurement[] measurements)
 {
     if ((object)measurements != null)
     {
         foreach (IMeasurement measurement in measurements)
         {
             MeasurementWrapper wrapper = new MeasurementWrapper(measurement);
             m_measurementCollection.Insert(wrapper);
         }
     }
 }
コード例 #7
0
ファイル: MongoHelper.cs プロジェクト: mabing377/DataDeal
 /// <summary>
 /// 插入多个数据
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="collectionName"></param>
 /// <param name="entiry"></param>
 public static void InsertAll <T>(string collectionName, IEnumerable <T> entity) where T : class
 {
     using (Mongo mongo = new Mongo(connectionString))
     {
         mongo.Connect();
         IMongoDatabase       friends    = mongo.GetDatabase(database);
         IMongoCollection <T> collection = friends.GetCollection <T>(collectionName);
         collection.Insert(entity, true);
         mongo.Disconnect();
     }
 }
コード例 #8
0
        /// <summary>
        /// Inserts a new document.
        /// </summary>
        /// <param name="orders">The orders.</param>
        private static void CreateAndInsertDocumentIntoCollection(IMongoCollection orders)
        {
            // Create a new order.
            var order = new Document();
            order["orderAmount"] = 57.22;
            order["customerName"] = "Elmer Fudd";

            // Add the new order to the mongo orders colleciton.
            orders.Insert(order);
            Console.WriteLine(string.Format("Inserted: {0}", order));
        }
コード例 #9
0
        public void TestFindAndModifyReturnsNewDocument()
        {
            IMongoCollection collection = DB["find_and_modify"];
            Document         person     = new Document().Append("First", "Susie").Append("Last", "O'Hara");

            collection.Insert(person);

            Document spec   = new Document().Append("_id", person["_id"]);
            Document loaded = collection.FindAndModify(new Document().Append("First", "Darlene"), spec, true);

            Assert.AreEqual("Darlene", loaded["First"]);
        }
コード例 #10
0
        public static bool InsertDocumentFromMEMBER(IMongoCollection <Document> coll, DEALERSHIP val)
        {
            bool     ret = true;
            Document doc = new Document();

            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.Insert(doc);
            return(ret);
        }
コード例 #11
0
        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"]);
        }
コード例 #12
0
        public void TestFindAndModifyReturnsOldDocument()
        {
            IMongoCollection collection = DB["find_and_modify"];
            Document         person     = new Document().Append("First", "Sally").Append("Last", "Simmons");

            collection.Insert(person);

            Document spec   = new Document().Append("_id", person["_id"]);
            Document loaded = collection.FindAndModify(new Document().Append("First", "Jane"), spec);

            Assert.AreEqual("Sally", loaded["First"]);
        }
コード例 #13
0
        public void TestCount()
        {
            IMongoCollection counts = db["tests"]["counts"];
            int top = 100;

            for (int i = 0; i < top; i++)
            {
                counts.Insert(new Document().Append("Last", "Cordr").Append("First", "Sam").Append("cnt", i));
            }
            long cnt = counts.Count();

            Assert.AreEqual(top, cnt, "Count not the same as number of inserted records");
        }
コード例 #14
0
        public void TestUpdateMany()
        {
            IMongoCollection updates = db["tests"]["updates"];

            updates.Insert(new Document().Append("Last", "Cordr").Append("First", "Sam"));
            updates.Insert(new Document().Append("Last", "Cordr").Append("First", "Sam2"));
            updates.Insert(new Document().Append("Last", "Cordr").Append("First", "Sam3"));

            Document selector = new Document().Append("Last", "Cordr");
            ICursor  results  = updates.Find(selector);
            bool     found    = false;

            foreach (Document doc in results.Documents)
            {
                Assert.AreEqual("Cordr", doc["Last"]);
                found = true;
            }
            Assert.IsTrue(found, "Should have found docs inserted for TestUpdateMany");
            Assert.AreEqual(3, updates.Count(selector), "Didn't find all Documents inserted for TestUpdateMany with Selector");

            //Document updateData = new Document().Append("$set", new Document().Append("Last", "Corder2"));
            Document updateData = new Document().Append("Last", "Corder2");

            updates.UpdateAll(updateData, selector);

            selector["Last"] = "Corder2";
            Assert.AreEqual(3, updates.Count(selector), "Not all Cordr documents were updated");

            results = updates.Find(selector);
            found   = false;
            foreach (Document doc in results.Documents)
            {
                Assert.AreEqual("Corder2", doc["Last"]);
                Assert.IsNotNull(doc["First"], "First name should not disappear");
                found = true;
            }
            Assert.IsTrue(found, "Should have found docs updated for TestMany");
        }
コード例 #15
0
        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();
        }
コード例 #16
0
        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"]);
        }
コード例 #17
0
        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"]);
        }
コード例 #18
0
        public void TestGetLastError()
        {
            IMongoCollection errcol = db["errcol"];

            errcol.MetaData.CreateIndex(new Document()
            {
                { "x", IndexOrder.Ascending }
            }, true);
            Document dup = new Document()
            {
                { "x", 1 }, { "y", 2 }
            };

            errcol.Insert(dup);
            Document error = db.GetLastError();

            Assert.AreEqual(MongoDBNull.Value, error["err"]);

            errcol.Insert(dup);
            error = db.GetLastError();

            Assert.IsFalse(MongoDBNull.Value == error["err"]);
        }
コード例 #19
0
        public static bool InsertDocumentFromMEMBER(IMongoCollection <Document> coll, PRICERANGE val)
        {
            bool     ret = true;
            Document doc = new Document();

            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.Insert(doc);
            return(ret);
        }
コード例 #20
0
        public static bool InsertDocumentFromMEMBER(IMongoCollection <Document> coll, IMAGE val)
        {
            bool ret = true;

            Document doc = new Document();

            doc["IMAGEID"]     = val.ImageId;
            doc["CONTENTTYPE"] = val.ContentType;
            doc["IMAGEDATA"]   = new Binary(val.ImageData);;
            doc["IMAGENAME"]   = val.ImageName;
            doc["TIMESSERVED"] = val.TimesServed;
            coll.Insert(doc);
            return(ret);
        }
コード例 #21
0
        public void AddUser(string username, string password)
        {
            IMongoCollection users = db["system.users"];
            string           pwd   = Database.Hash(username + ":mongo:" + password);
            Document         user  = new Document().Append("user", username).Append("pwd", pwd);

            if (FindUser(username) != null)
            {
                throw new MongoException("A user with the name " + username + " already exists in this database.", null);
            }
            else
            {
                users.Insert(user);
            }
        }
コード例 #22
0
        protected IMongoCollection InitCollection(string name)
        {
            IMongoCollection col = DB[name];

            col.Metadata.CreateIndex(new Document {
                { "x", IndexOrder.Ascending }
            }, true);
            for (int x = 0; x < 5; x++)
            {
                col.Insert(new Document {
                    { "x", x }, { "y", 1 }
                });
            }
            return(col);
        }
コード例 #23
0
        public void TestBadInsert()
        {
            IMongoCollection col    = InitCollection("safeinsert");
            bool             thrown = false;

            try{
                col.Insert(new Document {
                    { "x", 1 }, { "y", 2 }
                }, true);
            }catch (MongoDuplicateKeyException) {
                thrown = true;
            }catch (Exception e) {
                Assert.Fail(String.Format("Wrong exception thrown: {0}", e.GetType().Name));
            }
            Assert.IsTrue(thrown);
        }
コード例 #24
0
        /// <summary>
        /// Inserts a new document.
        /// </summary>
        /// <param name="orders">The orders.</param>
        private static void CreateAndInsertSingleDocumentIntoCollection( IMongoCollection orders )
        {
            Console.WriteLine( "\n\n======= Insert Multiple Documents =======" );
            Console.WriteLine( string.Format( "Document Count Before Insert: [ {0} ]", orders.Count() ) );

            // Create a new order.
            var order = new Document();
            order["OrderAmount"] = 57.22;
            order["CustomerName"] = "Elmer Fudd";

            // Add the new order to the mongo orders colleciton.
            orders.Insert( order );
            Console.WriteLine( string.Format( "Inserted: {0}", order ) );

            Console.WriteLine( string.Format( "Document Count After Insert: [ {0} ]", orders.Count() ) );
        }
コード例 #25
0
        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"]);
        }
コード例 #26
0
        public void TestReferenceNonOid()
        {
            Database         tests = mongo["tests"];
            IMongoCollection refs  = tests["refs"];

            Document doc = new Document().Append("_id", 123).Append("msg", "this has a non oid key");

            refs.Insert(doc);

            DBRef rf = new DBRef("refs", 123);

            Document recv = tests.FollowReference(rf);

            Assert.IsNotNull(recv);
            Assert.IsTrue(recv.Contains("msg"));
            Assert.AreEqual(recv["_id"], (long)123);
        }
コード例 #27
0
ファイル: MongoCollectionTests.cs プロジェクト: zulkamal/NoRM
        public void MapReduceIsSuccessful()
        {
            var _map    = "function(){emit(0, this.Price);}";
            var _reduce = "function(key, values){var sumPrice = 0;for(var i = 0; i < values.length; ++i){sumPrice += values[i];} return sumPrice;}";

            using (var mongo = Mongo.Create(TestHelper.ConnectionString("pooling=false&strict=false")))
            {
                mongo.Database.DropCollection("ReduceProduct");
                IMongoCollection <ReduceProduct> collection = mongo.GetCollection <ReduceProduct>();
                collection.Insert(new ReduceProduct {
                    Price = 1.5f
                }, new ReduceProduct {
                    Price = 2.5f
                });
                var r = collection.MapReduce <ProductSum>(_map, _reduce).FirstOrDefault();

                Assert.Equal(4, r.Value);
            }
        }
コード例 #28
0
        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");
        }
コード例 #29
0
        /// <summary>
        /// Demo inserting multiple document into collection.
        /// </summary>
        /// <param name="orders">The orders.</param>
        private static void CreateAndInsertMultipleDocumentIntoCollection( IMongoCollection 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 Document();
            order1["OrderAmount"] = 100.23;
            order1["CustomerName"] = "Bugs Bunny";

            var order2 = new Document();
            order2["OrderAmount"] = 0.01;
            order2["CustomerName"] = "Daffy Duck";

            IEnumerable< Document > orderList = new List< Document > {order1, order2};

            // Insert an IEnumerable.
            orders.Insert( 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() ) );
        }
コード例 #30
0
        /// <summary>
        ///   Setup the collection and insert some data into it.
        /// </summary>
        public void Setup()
        {
            var connstr = ConfigurationManager.AppSettings["simple"];

            if (String.IsNullOrEmpty(connstr))
            {
                throw new ArgumentNullException("Connection string not found.");
            }
            mongo = new Mongo(connstr);
            mongo.Connect();
            simple     = mongo["simple"];
            categories = simple.GetCollection <Document>("categories");
            Clean();

            var names = new[] { "Bluez", "Jazz", "Classical", "Rock", "Oldies", "Heavy Metal" };

            foreach (var name in names)
            {
                categories.Insert(new Document {
                    { "name", name }
                });
            }
        }
コード例 #31
0
        public override MembershipUser CreateUser(string username, string password, string email,
                                                  string passwordQuestion, string passwordAnswer,
                                                  bool isApproved, object providerUserKey,
                                                  out MembershipCreateStatus status)
        {
            var user = new MongoDBMembershipUser()
            {
                ProviderName     = this.Name, Username = username, Password = password, Email = email,
                PasswordQuestion = passwordQuestion, PasswordAnswer = passwordAnswer,
                IsApproved       = isApproved, IsLockedOut = false, ProviderUserKey = providerUserKey,
                LastActivityDate = DateTime.UtcNow,
            };

            try{
                members.Insert(user, true);
            }catch (MongoDuplicateKeyException) {
                status = MembershipCreateStatus.DuplicateUserName;
            }catch (MongoException) {
                status = MembershipCreateStatus.ProviderError;
            }
            status = MembershipCreateStatus.Success;
            return((MembershipUser)user);
        }
コード例 #32
0
        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());
        }
コード例 #33
0
ファイル: WhereQualifierTests.cs プロジェクト: zulkamal/NoRM
        public void MultiQualifierAnd()
        {
            _collection.Insert(new TestClass {
                AInteger = 78
            },
                               new TestClass {
                AInteger = 79
            },
                               new TestClass {
                AInteger = 80
            },
                               new TestClass {
                AInteger = 81
            });

            var result = _collection.Find(new { AInteger = Q.LessThan(81).And(Q.GreaterThan(78)) }).ToArray();

            Assert.Equal(2, result.Length);
            Assert.Equal(79, result[0].AInteger);
            Assert.Equal(80, result[1].AInteger);
        }
コード例 #34
0
ファイル: Main.cs プロジェクト: gaoninggn/mongodb-csharp
        /// <summary>
        ///   Setup the collection and insert some data into it.
        /// </summary>
        public void Setup()
        {
            var connstr = ConfigurationManager.AppSettings["simple"];
            if(String.IsNullOrEmpty(connstr))
                throw new ArgumentNullException("Connection string not found.");
            mongo = new Mongo(connstr);
            mongo.Connect();
            simple = mongo["simple"];
            categories = simple.GetCollection<Document>("categories");
            Clean();

            var names = new[] {"Bluez", "Jazz", "Classical", "Rock", "Oldies", "Heavy Metal"};
            foreach(var name in names)
                categories.Insert(new Document {{"name", name}});
        }
コード例 #35
0
 public static void Add <T>(this IMongoCollection <T> helper, T row) where T : TDocument
 {
     helper.Insert(row);
 }
コード例 #36
0
 /// <summary>
 /// Inserts documents
 /// </summary>
 /// <param retval="documentsToInsert">
 /// The documents to insert.
 /// </param>
 public static void Insert <T>(this IMongoCollection <T> collection, params T[] documentsToInsert)
 {
     collection.Insert(documentsToInsert.AsEnumerable());
 }
コード例 #37
0
        public void FindOneReturnsSomething()
        {
            _coll.Insert(new TestClass {
                ADouble = 1d
            });
            var found = _coll.FindOne(new { ADouble = 1d });

            Assert.NotNull(found);
        }
コード例 #38
0
        //
        // Insert/Delete Methods

        public void Add(Dinner dinner)
        {
            //db.Dinners.InsertOnSubmit(dinner);
            dinners.Insert(dinner);
        }
コード例 #39
0
ファイル: QueryTests.cs プロジェクト: zulkamal/NoRM
        public void FindUsesLimit()
        {
            _collection.Insert(new Person {
                Name = "BBB"
            });
            _collection.Insert(new Person {
                Name = "CCC"
            });
            _collection.Insert(new Person {
                Name = "AAA"
            });
            _collection.Insert(new Person {
                Name = "DDD"
            });

            var result = _collection.Find(new { }, 3).ToArray();

            Assert.Equal(3, result.Length);
        }