コード例 #1
0
ファイル: UpdateTests.cs プロジェクト: zulkamal/NoRM
 public void Update_Multiple_With_Lambda_Works()
 {
     _collection.Insert(new CheeseClubContact {
         Name = "Hello"
     }, new CheeseClubContact {
         Name = "World"
     });
     _collection.Update(new { Name = Q.NotEqual("") }, h => h.SetValue(y => y.Name, "Cheese"), true, false);
     Assert.Equal(2, _collection.Find(new { Name = "Cheese" }).Count());
 }
コード例 #2
0
ファイル: MongodbExtension.cs プロジェクト: fryg123/ColorCMS
        /// <summary>
        /// 更新子文档
        /// </summary>
        /// <typeparam name="TDocument"></typeparam>
        /// <typeparam name="TField"></typeparam>
        /// <typeparam name="TSaveField"></typeparam>
        /// <param name="collection"></param>
        /// <param name="filter">查询语句</param>
        /// <param name="memberExpression">要更新的字段</param>
        /// <param name="value">要更新的值</param>
        /// <returns></returns>
        public static UpdateResult SaveChildren <TDocument, TField, TSaveField>(this IMongoCollection <TDocument> collection, Expression <Func <TDocument, bool> > filter, Expression <Func <TDocument, TField> > memberExpression, TSaveField value)
        {
            var pInfos        = value.GetType().GetProperties();
            var updateBuilder = collection.GetUpdate();
            var field         = memberExpression.Body.ToString().Split('.')[1];

            foreach (var p in pInfos)
            {
                if (p.Name == "Id")
                {
                    continue;
                }
                var       pValue    = p.GetValue(value, null);
                BsonValue bsonValue = null;
                if (pValue != null)
                {
                    if (pValue.GetType().Name == "Decimal")
                    {
                        bsonValue = BsonValue.Create((double)pValue);
                    }
                    else
                    {
                        bsonValue = BsonValue.Create(pValue);
                    }
                    updateBuilder = updateBuilder.Set(string.Format("{0}.$.{1}", field, p.Name), bsonValue);
                }
            }
            return(collection.Update(filter, updateBuilder));
        }
コード例 #3
0
        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"]);
        }
コード例 #4
0
        /// <summary>
        /// Flushes any changes to current chunk to the database.  It can be called in client code at any time or it
        /// will automatically be called on Close() and when the stream position moves off the bounds of the current
        /// chunk.
        /// </summary>
        public override void Flush()
        {
            if (chunkDirty == false)
            {
                return;
            }
            //avoid a copy if possible.
            if (highestBuffPosition == buffer.Length)
            {
                chunk["data"] = new Binary(buffer);
            }
            else
            {
                byte[] data = new byte[highestBuffPosition];
                Array.Copy(buffer, data, highestBuffPosition);
                chunk["data"] = new Binary(data);
            }


            if (chunk.Contains("_id"))
            {
                chunks.Update(chunk);
            }
            else
            {
                chunks.Insert(chunk);
            }
            this.gridFileInfo.Length = highestPosWritten;
        }
コード例 #5
0
ファイル: MongoHelper.cs プロジェクト: mabing377/DataDeal
 /// <summary>
 /// 更新操作
 /// </summary>
 /// <typeparam name="T">类型</typeparam>
 /// <param name="collectionName">表名</param>
 /// <param name="query">条件</param>
 /// <param name="entry">新实体</param>
 public static void Update <T>(string collectionName, Document entity, Document query) where T : class
 {
     using (Mongo mongo = new Mongo(connectionString))
     {
         mongo.Connect();
         IMongoDatabase       friends    = mongo.GetDatabase(database);
         IMongoCollection <T> collection = friends.GetCollection <T>(collectionName);
         collection.Update(entity, query, true);
         mongo.Disconnect();
     }
 }
コード例 #6
0
        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"]);
        }
コード例 #7
0
ファイル: HitCountDatabase.cs プロジェクト: zgren/dp2
        // 增加一次访问计数
        // return:
        //      false   没有成功。通常因为 mongodb 无法打开等原因
        //      true    成功
        public bool IncHitCount(string strURL)
        {
            IMongoCollection <HitCountItem> collection = this.HitCountCollection;

            if (collection == null)
            {
                return(false);
            }

            var query  = new QueryDocument("URL", strURL);
            var update = Update.Inc("HitCount", 1);

            collection.Update(
                query,
                update,
                UpdateFlags.Upsert);
            return(true);
        }
コード例 #8
0
        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();
        }
コード例 #9
0
        public void TestBadUpdate()
        {
            IMongoCollection col    = InitCollection("safeupdate");
            bool             thrown = false;

            try{
                col.Update(new Document {
                    { "x", 1 }
                }, new Document {
                    { "x", 2 }
                }, true);
            }catch (MongoDuplicateKeyUpdateException) {
                thrown = true;
            }catch (MongoDuplicateKeyException) {
                Assert.Fail("MongoDuplicateKeyException thown instead of MongoDuplicateKeyUpdateException");
            }catch (Exception e) {
                Assert.Fail(String.Format("Wrong exception thrown: {0}", e.GetType().Name));
            }
            Assert.IsTrue(thrown);
        }
コード例 #10
0
        public async Task EmitEventOnUpdate()
        {
            // Arrange
            var calculation = new Calculation(calculationId);

            calculation.Add(2);
            await calculations.Create(calculation);

            calculation.MultiplyBy(2);
            var futureEvent = observable.FirstOfType <NumberMultiplied>(calculationId);

            // Act
            await calculations.Update(calculation);

            // Assert
            calculation.Events.Should().BeEmpty();
            var @event = await futureEvent;

            @event.SourceId.Should().Be(calculationId);
            @event.Result.Should().Be(4);
        }
コード例 #11
0
        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["MILEAGE"]         = val.MILEAGE;
            doc["CURRENT_PRICE"]   = val.CURRENT_PRICE;
            doc["VEHICLE_HISTORY"] = val.VEHICLE_HISTORY;
            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["DATE_LAST_SEEN"]  = val.DATE_LAST_SEEN.ToShortDateString();
            coll.Update(doc);
            return(ret);
        }
コード例 #12
0
        public static void AddFailChar(IMongoCollection <FailChar> failCharSet, int failCode, ushort unicode, string text, string failMessage)
        {
            FailChar failChar = null;

            if ((failChar = failCharSet.FirstOrDefault(f => f.Unicode == unicode)) != null)
            {
                failChar.FailCode     = failCode;
                failChar.FailMessage  = failMessage;
                failChar.ModifiedTime = DateTime.Now;
                failCharSet.Update(failChar);
            }
            else
            {
                failCharSet.Add(new FailChar
                {
                    FailCode     = 1,
                    Unicode      = unicode,
                    Text         = text,
                    FailMessage  = failMessage,
                    CreatedTime  = DateTime.Now,
                    ModifiedTime = DateTime.Now,
                });
            }
        }
コード例 #13
0
        /// <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));
        }
コード例 #14
0
        /// <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 ) );
        }
コード例 #15
0
ファイル: MongodbExtension.cs プロジェクト: fryg123/ColorCMS
        /// <summary>
        /// 添加子对象
        /// </summary>
        /// <typeparam name="TValue"></typeparam>
        /// <param name="filter">查询表达式</param>
        /// <param name="memberExpression">要更新的字段</param>
        /// <param name="values">更新到该字段的数组</param>
        public static UpdateResult AddChild <TDocument, TValue>(this IMongoCollection <TDocument> collection, Expression <Func <TDocument, bool> > filter, Expression <Func <TDocument, IEnumerable <TValue> > > field, params TValue[] values)
        {
            var update = Builders <TDocument> .Update.PushEach(field, values);

            return(collection.Update(filter, update));
        }
コード例 #16
0
ファイル: LinqExtensions.cs プロジェクト: youlin1210/MySample
 /// <summary>
 /// Updates the selectorified collection.
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="collection">The collection.</param>
 /// <param name="document">The document.</param>
 /// <param name="selector">The selector.</param>
 public static void Update <T>(this IMongoCollection <T> collection, object document, Expression <Func <T, bool> > selector) where T : class
 {
     collection.Update(document, GetQuery(collection, selector));
 }
コード例 #17
0
ファイル: LinqExtensions.cs プロジェクト: youlin1210/MySample
 /// <summary>
 /// Updates the selectorified collection.
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="collection">The collection.</param>
 /// <param name="document">The document.</param>
 /// <param name="selector">The selector.</param>
 /// <param name="flags">The flags.</param>
 /// <param name="safeMode">if set to <c>true</c> [safe mode].</param>
 public static void Update <T>(this IMongoCollection <T> collection, object document, Expression <Func <T, bool> > selector, UpdateFlags flags, bool safeMode) where T : class
 {
     collection.Update(document, GetQuery(collection, selector), flags, safeMode);
 }
コード例 #18
0
        public Task GetTask()
        {
            Task task = Task.Run(async() =>
            {
                await Init();
                ushort begIndex = crawlerInfo.Unicode == 0 ? beginUnicode : crawlerInfo.Unicode;
                if (crawlerInfo.IsCompleted)
                {
                    return;
                }

                string text = string.Empty;

                if (chineseCharSet.Any(a => a.Unicode == begIndex))
                {
                    begIndex++;
                }

                for (ushort i = begIndex; i <= endUnicode; ++i)
                {
                    text = Convert.ToChar(i).ToString();
                    try
                    {
                        ChineseChar chineseChar = await GetOneChinese(httpClient, uri, i, len1, len2);
                        if (chineseChar == null)
                        {
                            PrintFail(0, i, text);
                            AddFailChar(failCharSet, 0, i, text, "");
                            continue;
                        }

                        chineseCharSet.Add(chineseChar);
                        crawlerInfo.Unicode      = i;
                        crawlerInfo.ModifiedTime = DateTime.Now;
                        crawlerInfoSet.Update(crawlerInfo);
                        Console.WriteLine($"完成记录 Unicode编码:{i} 字符内容:{text}");
                    }
                    catch (Exception ex)
                    {
                        PrintFail(1, i, text);
                        AddFailChar(failCharSet, 1, i, text, ex.Message);
                    }
                    finally
                    {
                        await Task.Delay(200);
                    }
                }
            }).ContinueWith(t =>
            {
                var foregroundColor = ConsoleColor.White;
                if (t.IsCompletedSuccessfully == false)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine(t.Exception.ToString());
                    Console.ForegroundColor = foregroundColor;
                }

                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine($"{beginUnicode}~{endUnicode} 爬虫完成");
                Console.ForegroundColor = foregroundColor;

                httpClient.Dispose();
                if (t.IsCompletedSuccessfully)
                {
                    crawlerInfo.IsCompleted = true;
                    crawlerInfoSet.Update(crawlerInfo);
                }
                t.Dispose();
            });

            return(task);
        }
コード例 #19
0
 /// <summary>Allows a document to be updated using the specified action.</summary>
 public static void Update <T, X>(this IMongoCollection <T> collection, X matchDocument, Action <IModifierExpression <T> > action)
 {
     collection.Update(matchDocument, action, false, false);
 }
コード例 #20
0
 /// <summary>
 /// Overload of Update that updates one document and doesn't upsert if no matches are found.
 /// </summary>
 /// <typeparam retval="X">Document to match</typeparam>
 /// <typeparam retval="U">Value document</typeparam>
 /// <param retval="matchDocument">The match Document.</param>
 /// <param retval="valueDocument">The value Document.</param>
 public static void UpdateOne <T, X, U>(this IMongoCollection <T> collection, X matchDocument, U valueDocument)
 {
     collection.Update(matchDocument, valueDocument, false, false);
 }
コード例 #21
0
ファイル: UpdateModifiersTests.cs プロジェクト: zulkamal/NoRM
        public void PullingTag_NoSql_FromPostWith_NoSql_TagWithPullModifierShouldRemoveThatTag()
        {
            var post = new Post {
                Title = "About the name 2", Score = 3
            };

            post.Tags.Add("NoSql");
            _collection.Insert(post);

            _collection.Update(post.Id, op => op.Pull(prop => prop.Tags, "NoSql"));

            var result = _collection.FindOne(new { _id = post.Id });

            Assert.Equal(0, result.Tags.Count);
            Assert.Equal(3, result.Score);
            Assert.Equal("About the name 2", result.Title);
        }