当前位置: 首页>>代码示例>>C#>>正文


C# IMongoCollection.InsertOneAsync方法代码示例

本文整理汇总了C#中IMongoCollection.InsertOneAsync方法的典型用法代码示例。如果您正苦于以下问题:C# IMongoCollection.InsertOneAsync方法的具体用法?C# IMongoCollection.InsertOneAsync怎么用?C# IMongoCollection.InsertOneAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在IMongoCollection的用法示例。


在下文中一共展示了IMongoCollection.InsertOneAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: SaveRecord

        /// <summary>
        /// Saves a record to database.
        /// </summary>
        /// <returns>The record.</returns>
        /// <param name="collection">Collection.</param>
        private static async Task SaveRecord(IMongoCollection<PhoneBookRecord> collection)
        {
            Console.WriteLine("Enter a name:");
            string name = Console.ReadLine();
            Console.WriteLine("Enter a phone:");
            string phone = Console.ReadLine();

            PhoneBookRecord record = new PhoneBookRecord(){ Name = name, Phone = phone };

            await collection.InsertOneAsync(record);
        }
开发者ID:Julia-Berezhnova,项目名称:Semester-2,代码行数:16,代码来源:Program.cs

示例2: InsertToDatabase

        private static void InsertToDatabase(IMongoCollection<EnergyDrink> collection)
        {
            Console.Clear();
            Console.Write("Enter the name of the drink:");
            var name = Console.ReadLine();
            Console.Write("\nEnter the price of the drink:");
            var price = double.Parse(Console.ReadLine());

            var energyDrink = new EnergyDrink(name, price);
            collection.InsertOneAsync(energyDrink);

            Console.WriteLine("The drink was successfuly added");
            Console.WriteLine("\nPress any key to continue..");
            Console.ReadLine();
        }
开发者ID:ni4ka7a,项目名称:TelerikAcademyHomeworks,代码行数:15,代码来源:EntryPoint.cs

示例3: Execute

 protected override void Execute(IMongoCollection<BsonDocument> collection, BsonDocument outcome, bool async)
 {
     if (async)
     {
         collection.InsertOneAsync(_document).GetAwaiter().GetResult();
     }
     else
     {
         collection.InsertOne(_document);
     }
 }
开发者ID:RavenZZ,项目名称:MDRelation,代码行数:11,代码来源:InsertOneTest.cs

示例4: ExecuteAsync

        public async Task ExecuteAsync(UpsertClimbCommandParameters parameters, IMongoCollection<Climb> collection)
        {
            var climb = new Climb
            {
                Id = parameters.Id,
                LatLong = parameters.LatLong,
                Rating = parameters.Rating,
                Styles = parameters.Styles,
                Name = parameters.Name
            };

            if (parameters.Id == Guid.Empty)
            {
                await collection.InsertOneAsync(climb);
            }
            else
            {
                var filter = Builders<Climb>.Filter.Eq(c => c.Id == climb.Id, true);
                await collection.UpdateOneAsync(filter, new ObjectUpdateDefinition<Climb>(climb));
            }
        }
开发者ID:MikeBeastall,项目名称:MonkeyStrong,代码行数:21,代码来源:UpsertClimbCommand.cs

示例5: GetFutureTweets

        private async Task GetFutureTweets(string user, IMongoCollection<BsonDocument> tweets)
        {
            int tweetsCount = 0, tweetsProcessed = 0, tweetsMax = MaxTweets;
            var filter = GetFilter(user);
            var aggdef = tweets.Aggregate()
                .Match(filter)
                .Group(new BsonDocument { { "_id", "$user.screen_name" }, { "max", new BsonDocument("$max", "$id") } });
            var aggresult = await aggdef.FirstOrDefaultAsync();
            var maxid = aggresult["max"].AsNullableInt64;

          


            do
            {
                var query = string.Format(api_path, user);

                if (maxid.HasValue)
                {
                    query = query + "&since_id={0}";
                    query = string.Format(query, maxid + 1);
                }

                var jsonObject = TwitterDownloader.ExecuteJsonGETQuery(query);
                List<object> otweets = (List<object>)JsonConvert.DeserializeObject<List<object>>(jsonObject);
                tweetsCount = otweets.Count;
                tweetsProcessed += tweetsCount;
                _log.Info("Getting {0} new tweets for user:{1}", otweets.Count, user);

                foreach (object oTweet in otweets)
                {
                    var bson = BsonDocument.Parse(oTweet.ToString());
                    tweets.InsertOneAsync(bson).Wait();
                    long? nmax = bson["id"].AsNullableInt64;
                    if (nmax > maxid)
                        maxid = nmax;
                }
            }
            while (tweetsCount > 0 && tweetsProcessed < tweetsMax);
        }
开发者ID:johnnytorres,项目名称:twitterlc,代码行数:40,代码来源:TwitterHomelineHandlerMongo.cs

示例6: Dr

        private static async Task Dr(IMongoCollection<BsonDocument> leaders, BsonDocument filter, IMongoCollection<BsonDocument> users, IMongoCollection<BsonDocument> leadersbak)
        {
            using (var cursor = await leaders.FindAsync(filter))
            {

                while (await cursor.MoveNextAsync())
                {
                    var batch = cursor.Current;
                    foreach (var rt in batch)
                    {
                        BsonArray bRetweeters = rt["retweeters_id"].AsBsonArray;

                        //if (bRetweeters.Count == 0)
                        //    continue;

                        foreach (var bUser in bRetweeters)
                        {
                            var lUser = bUser.ToInt64();
                            try
                            {

                                log.Info("readling retweeter {0}", lUser);
                                var usersFilter = Builders<BsonDocument>.Filter.Eq("id", lUser);
                                var result = await users.Find(usersFilter).ToListAsync();
                                if (result.Count > 0)
                                    continue;

                                log.Info("downloading retweeter {0}", lUser);
                                TwitterProfileHandler profileHandler = new TwitterProfileHandlerMongo();
                                string screenName = profileHandler.Download(lUser);
                                //TwitterHomelineHandler homeHandler = new TwitterHomelineHandlerMongo();
                                //homeHandler.Download(screenName);
                            }
                            catch (Exception ex)
                            {
                                string msg = "Error trying to download profile for user:{0}";
                                msg = string.Format(msg, lUser);
                                log.Error(ex, msg);
                            }
                        }

                        //rt["done"] = true;
                        //var filterupdate = Builders<BsonDocument>.Filter.Eq("_id", rt["_id"]);
                        //var update = Builders<BsonDocument>.Update.Push("done", true);
                        //await leaders.UpdateOneAsync(filterupdate, rt);
                        await leadersbak.InsertOneAsync(rt);
                        var filterbak = Builders<BsonDocument>.Filter.Eq("_id", rt["_id"]);
                        await leaders.DeleteOneAsync(filterbak);
                    }
                }
            }

            Thread.Sleep(5000);
        }
开发者ID:johnnytorres,项目名称:twitterlc,代码行数:54,代码来源:Program.cs

示例7: DoWork

        private async Task DoWork(IMongoCollection<BsonDocument> collection)
        {
            var rand = new Random();
            while (!_cancellationTokenSource.IsCancellationRequested)
            {
                var i = rand.Next(0, 10000);
                List<BsonDocument> docs;
                try
                {
                    docs = await collection.Find(new BsonDocument("i", i))
                        .ToListAsync(_cancellationTokenSource.Token);
                }
                catch
                {
                    Console.Write("+");
                    continue;
                }

                if (docs.Count == 0)
                {
                    try
                    {
                        await collection.InsertOneAsync(new BsonDocument("i", i), _cancellationTokenSource.Token);
                    }
                    catch
                    {
                        Console.Write("*");
                    }
                }
                else
                {
                    try
                    {
                        var filter = new QueryDocument("_id", docs[0]["_id"]);
                        var update = new UpdateDocument("$set", new BsonDocument("i", i + 1));
                        await collection.UpdateOneAsync(filter, update, cancellationToken: _cancellationTokenSource.Token);
                        //Console.Write(".");
                    }
                    catch (Exception)
                    {
                        Console.Write("*");
                    }
                }
            }
        }
开发者ID:kay-kim,项目名称:mongo-csharp-driver,代码行数:45,代码来源:Api.cs

示例8: GetHistoricalTweets

        private async Task GetHistoricalTweets(string user, IMongoCollection<BsonDocument> tweets)
        {
            int tweetsCount = 0, tweetsProcessed = 0, tweetsMax = MaxTweets;
            //var filter = GetFilter(user);
            //var aggdef = tweets.Aggregate()
            //    .Match(filter)
            //    .Group(new BsonDocument { { "_id", "$user.screen_name" }, { "min", new BsonDocument("$min", "$id") } });
            //var aggresult = await aggdef.FirstOrDefaultAsync();
            //var minid = aggresult != null ? aggresult["min"].AsNullableInt64 : null;

           
            //do
            //{
                var query = string.Format(api_path, user);

                //if (minid.HasValue)
                //{
                //    query = query + "&max_id={0}";
                //    query = string.Format(query, minid - 1);
                //}

                var jsonObject = TwitterDownloader.ExecuteJsonGETQuery(query);

                if (jsonObject == null)
                    return;

                List<object> otweets = (List<object>)JsonConvert.DeserializeObject<List<object>>(jsonObject);
                tweetsCount = otweets.Count;
                tweetsProcessed += tweetsCount;
                Console.WriteLine("Getting {0} old tweets for user:{1}", otweets.Count, user);

                foreach (object oTweet in otweets)
                {
                    var bson = BsonDocument.Parse(oTweet.ToString());
                    tweets.InsertOneAsync(bson).Wait();
                    //minid = bson["id"].AsNullableInt64;
                }
            //}
            //while (tweetsCount > 0 && tweetsProcessed < tweetsMax);
        }
开发者ID:johnnytorres,项目名称:twitterlc,代码行数:40,代码来源:TwitterHomelineHandlerMongo.cs

示例9: AddDocuments

        static async Task AddDocuments(IMongoCollection<Person> collection)
        {
            var testdoc = new Person ("jones");
            testdoc.Age = 30;
            testdoc.Profession = "hacker";

            var nestedArray = new List<string>();
            nestedArray.Add("color");
            nestedArray.Add("red");
            testdoc.Preferences = nestedArray;
            await collection.InsertOneAsync(testdoc);
            Console.WriteLine("Adding:" + testdoc.ToBsonDocument().ToString());

            var testdoc2 = new Person("jones");
            testdoc2.Age = 50;
            testdoc2.Profession = "retired hacker";
            await collection.InsertOneAsync(testdoc2);
            Console.WriteLine("Adding:" + testdoc2.ToBsonDocument().ToString());

            var doc2 = new Person("Smith");
            var doc3 = new Person("White");
            await collection.InsertManyAsync(new[] { doc2, doc3 });
            Console.WriteLine("Adding:" + doc2.ToBsonDocument().ToString() + "\nAdding:" + doc3.ToBsonDocument().ToString());
        }
开发者ID:ax2015,项目名称:testprojects,代码行数:24,代码来源:Program.cs

示例10: InsertDocumentInCollection

 public async void InsertDocumentInCollection(BsonDocument document, IMongoCollection<BsonDocument> collection)
 {
     await  collection.InsertOneAsync(document);
 }
开发者ID:AzharIqbal84,项目名称:ForwardMongoLogger,代码行数:4,代码来源:MongoDbHelper.cs

示例11: AddMongo

 private static async Task AddMongo(BsonDocument doc, IMongoCollection<BsonDocument> collection)
 {
     await collection.InsertOneAsync(doc);
 }
开发者ID:JOKAZ12345,项目名称:u-mad-braWLER,代码行数:4,代码来源:Form1.cs

示例12: InsertOne

        /// <summary>
        /// Insert a new single document (SQL=row) in the collection (SQL=table).
        /// </summary>
        private static void InsertOne(IMongoCollection<BsonDocument> collection)
        {
            Console.WriteLine("++ Insert a new single document (SQL=row) in the collection (SQL=table).");

            //var document = new BsonDocument { {"_id", ObjectId.GenerateNewId()}, { "THE NEW ROW", "Document 1234567890" } };
            var document = new BsonDocument().AddRange(newObj);
            Task t = collection.InsertOneAsync(document);
            t.Wait();

            Console.WriteLine("  status = " + t.Status);
        }
开发者ID:sshev4enko,项目名称:tandd,代码行数:14,代码来源:Program.cs

示例13: InsertCustomer

 static async Task InsertCustomer(IMongoCollection<Customer> collection)
 {
     await collection.InsertOneAsync(new Customer());
 }
开发者ID:naveed-ahmad-biz,项目名称:MongoDBTestApp,代码行数:4,代码来源:Program.cs

示例14: ExecuteAsync

 protected override Task ExecuteAsync(IMongoCollection<BsonDocument> collection, BsonDocument outcome)
 {
     return collection.InsertOneAsync(_document);
 }
开发者ID:fir3pho3nixx,项目名称:mongo-csharp-driver,代码行数:4,代码来源:InsertOneTest.cs

示例15: CreateAdmin

		private async Task CreateAdmin(IMongoCollection<UserModel> users)
		{
 			await users.Indexes.CreateOneAsync(
				Builders<UserModel>.IndexKeys.Ascending(u => u.Name),
				new CreateIndexOptions { Unique = true, });

			if (await users.CountAsync(_ => true) == 0)
			{
				await users
					.InsertOneAsync(
					new UserModel
					{
						Name = AdminName,
						Password = AdminPassword,
						Roles = AdminRoles
					});
			}
		}
开发者ID:lexarchik,项目名称:BuildRevisionCounter,代码行数:18,代码来源:MongoUserRepository.cs


注:本文中的IMongoCollection.InsertOneAsync方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。