• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# BsonDocument类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中BsonDocument的典型用法代码示例。如果您正苦于以下问题:C# BsonDocument类的具体用法?C# BsonDocument怎么用?C# BsonDocument使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



BsonDocument类属于命名空间,在下文中一共展示了BsonDocument类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: AssertValid

        private void AssertValid(ConnectionString connectionString, BsonDocument definition)
        {
            if (!definition["valid"].ToBoolean())
            {
                Assert.Fail($"The connection string '{definition["uri"]}' should be invalid.");
            }

            BsonValue readConcernValue;
            if (definition.TryGetValue("readConcern", out readConcernValue))
            {
                var readConcern = ReadConcern.FromBsonDocument((BsonDocument)readConcernValue);

                connectionString.ReadConcernLevel.Should().Be(readConcern.Level);
            }

            BsonValue writeConcernValue;
            if (definition.TryGetValue("writeConcern", out writeConcernValue))
            {
                var writeConcern = WriteConcern.FromBsonDocument(MassageWriteConcernDocument((BsonDocument)writeConcernValue));

                connectionString.W.Should().Be(writeConcern.W);
                connectionString.WTimeout.Should().Be(writeConcern.WTimeout);
                connectionString.Journal.Should().Be(writeConcern.Journal);
                connectionString.FSync.Should().Be(writeConcern.FSync);
            }
        }
开发者ID:narutoswj,项目名称:mongo-csharp-driver,代码行数:26,代码来源:ConnectionStringTestRunner.cs


示例2: Map

        /// <summary>
        /// Maps the specified response to a custom exception (if possible).
        /// </summary>
        /// <param name="response">The response.</param>
        /// <returns>The custom exception (or null if the response could not be mapped to a custom exception).</returns>
        public static Exception Map(BsonDocument response)
        {
            BsonValue code;
            if (response.TryGetValue("code", out code) && code.IsNumeric)
            {
                switch (code.ToInt32())
                {
                    case 50:
                    case 13475:
                    case 16986:
                    case 16712:
                        return new ExecutionTimeoutException("Operation exceeded time limit.");
                }
            }

            // the server sometimes sends a response that is missing the "code" field but does have an "errmsg" field
            BsonValue errmsg;
            if (response.TryGetValue("errmsg", out errmsg) && errmsg.IsString)
            {
                if (errmsg.AsString.Contains("exceeded time limit") ||
                    errmsg.AsString.Contains("execution terminated"))
                {
                    return new ExecutionTimeoutException("Operation exceeded time limit.");
                }
            }

            return null;
        }
开发者ID:Bogdan0x400,项目名称:mongo-csharp-driver,代码行数:33,代码来源:ExceptionMapper.cs


示例3: TestInsertUpdateAndSaveWithElementNameStartingWithDollarSign

        public void TestInsertUpdateAndSaveWithElementNameStartingWithDollarSign()
        {
            var server = Configuration.TestServer;
            var database = Configuration.TestDatabase;
            var collection = Configuration.TestCollection;
            collection.Drop();

            var document = new BsonDocument
            {
                { "_id", 1 },
                { "v", new BsonDocument("$x", 1) } // server doesn't allow "$" at top level
            };
            var insertOptions = new MongoInsertOptions { CheckElementNames = false };
            collection.Insert(document, insertOptions);
            document = collection.FindOne();
            Assert.AreEqual(1, document["v"]["$x"].AsInt32);

            document["v"]["$x"] = 2;
            var query = Query.EQ("_id", 1);
            var update = Update.Replace(document);
            var updateOptions = new MongoUpdateOptions { CheckElementNames = false };
            collection.Update(query, update, updateOptions);
            document = collection.FindOne();
            Assert.AreEqual(2, document["v"]["$x"].AsInt32);

            document["v"]["$x"] = 3;
            collection.Save(document, insertOptions);
            document = collection.FindOne();
            Assert.AreEqual(3, document["v"]["$x"].AsInt32);
        }
开发者ID:CloudMetal,项目名称:mongo-csharp-driver,代码行数:30,代码来源:CSharp358Tests.cs


示例4: Post

        public void Post(UserModel model)
        {
            var mongoDbClient = new MongoClient("mongodb://127.0.0.1:27017");
            var mongoDbServer = mongoDbClient.GetDatabase("SocialNetworks");
            BsonArray arr = new BsonArray();            
            dynamic jobj = JsonConvert.DeserializeObject<dynamic>(model.Movies.ToString());
            foreach (var item in jobj)
            {
                foreach(var subitem in item)
                {
                    arr.Add(subitem.Title.ToString());
                }
            }

            var document = new BsonDocument
            {
                { "Facebook_ID",  model.Facebook_ID },
                { "Ime",  model.Ime  },
                { "Prezime",  model.Prezime  },
                { "Email",  model.Email  },
                { "DatumRodjenja",  model.DatumRodjenja  },
                { "Hometown", model.Hometown},
                { "ProfilePictureLink", model.ProfilePictureLink  },
                { "Movies",  arr },
            };

            var collection = mongoDbServer.GetCollection<BsonDocument>("UserInfo");
            collection.InsertOneAsync(document);
        }
开发者ID:IvanKresic,项目名称:SocialNetworkRecommander,代码行数:29,代码来源:UserInfoController.cs


示例5: ExplainOperationTests

 public ExplainOperationTests()
 {
     _command = new BsonDocument
     {
         { "count", _collectionNamespace.CollectionName }
     };
 }
开发者ID:RavenZZ,项目名称:MDRelation,代码行数:7,代码来源:ExplainOperationTests.cs


示例6: TestInsertUpdateAndSaveWithElementNameStartingWithDollarSign

        public void TestInsertUpdateAndSaveWithElementNameStartingWithDollarSign()
        {
            var server = MongoServer.Create("mongodb://localhost/?safe=true;slaveOk=true");
            var database = server["onlinetests"];
            var collection = database["test"];
            collection.Drop();

            var document = new BsonDocument
            {
                { "_id", 1 },
                { "v", new BsonDocument("$x", 1) } // server doesn't allow "$" at top level
            };
            var insertOptions = new MongoInsertOptions { CheckElementNames = false };
            collection.Insert(document, insertOptions);
            document = collection.FindOne();
            Assert.AreEqual(1, document["v"].AsBsonDocument["$x"].AsInt32);

            document["v"].AsBsonDocument["$x"] = 2;
            var query = Query.EQ("_id", 1);
            var update = Update.Replace(document);
            var updateOptions = new MongoUpdateOptions { CheckElementNames = false };
            collection.Update(query, update, updateOptions);
            document = collection.FindOne();
            Assert.AreEqual(2, document["v"].AsBsonDocument["$x"].AsInt32);

            document["v"].AsBsonDocument["$x"] = 3;
            collection.Save(document, insertOptions);
            document = collection.FindOne();
            Assert.AreEqual(3, document["v"].AsBsonDocument["$x"].AsInt32);
        }
开发者ID:kamaradclimber,项目名称:mongo-csharp-driver,代码行数:30,代码来源:CSharp358Tests.cs


示例7: BulkWriteError

 // constructors
 internal BulkWriteError(int index, int code, string message, BsonDocument details)
 {
     _code = code;
     _details = details;
     _index = index;
     _message = message;
 }
开发者ID:KeithLee208,项目名称:mongo-csharp-driver,代码行数:8,代码来源:BulkWriteError.cs


示例8: BsonDocumentReader

 public BsonDocumentReader(
     BsonDocument document
 )
 {
     context = new BsonDocumentReaderContext(null, ContextType.TopLevel, document);
     currentValue = document;
 }
开发者ID:modesto,项目名称:mongo-csharp-driver,代码行数:7,代码来源:BsonDocumentReader.cs


示例9: MainAsync

        static async Task MainAsync(string[] args)
        {
            var urlString = "mongodb://localhost:27017";
            var client = new MongoClient(urlString);
            var db = client.GetDatabase("students");
            var collection = db.GetCollection<BsonDocument>("grades");
            var filter = new BsonDocument("type","homework");
           // var count = 0;
            var sort = Builders<BsonDocument>.Sort.Ascending("student_id").Ascending("score");
            var result = await collection.Find(filter).Sort(sort).ToListAsync();
           var previous_id=-1 ;
           var student_id=-1;
            int count = 0;
            foreach (var doc in result)         
            {
                
                student_id = (int)doc["student_id"];
                    //Console.WriteLine(student_id);
                if (student_id != previous_id)
                {
                    count++;
                    previous_id = student_id;
                    Console.WriteLine("removing :{0} ", doc);
                   // await collection.DeleteOneAsync(doc);

                    await collection.DeleteManyAsync(doc);
                }



              // process document
            }
            Console.WriteLine(count);
            //Console.WriteLine(coll.FindAsync<"">);
        }
开发者ID:sahithrao153,项目名称:M101Dotnet,代码行数:35,代码来源:MongoDB.cs


示例10: CountFilteredWithBsonDocument

        public async Task CountFilteredWithBsonDocument()
        {
            BsonDocument filter = new BsonDocument("_id", "050305007");
            long count = await SchoolContext.StudentsAsBson.CountAsync(filter);

            count.Should().Be(1);
        }
开发者ID:emretiryaki,项目名称:NetMongoDbQueryTest,代码行数:7,代码来源:CountTests.cs


示例11: BsonBinaryReader_should_support_reading_multiple_documents

        public void BsonBinaryReader_should_support_reading_multiple_documents(
            [Range(0, 3)]
            int numberOfDocuments)
        {
            var document = new BsonDocument("x", 1);
            var bson = document.ToBson();
            var input = Enumerable.Repeat(bson, numberOfDocuments).Aggregate(Enumerable.Empty<byte>(), (a, b) => a.Concat(b)).ToArray();
            var expectedResult = Enumerable.Repeat(document, numberOfDocuments);

            using (var stream = new MemoryStream(input))
            using (var binaryReader = new BsonBinaryReader(stream))
            {
                var result = new List<BsonDocument>();

                while (!binaryReader.IsAtEndOfFile())
                {
                    binaryReader.ReadStartDocument();
                    var name = binaryReader.ReadName();
                    var value = binaryReader.ReadInt32();
                    binaryReader.ReadEndDocument();

                    var resultDocument = new BsonDocument(name, value);
                    result.Add(resultDocument);
                }

                result.Should().Equal(expectedResult);
            }
        }
开发者ID:narutoswj,项目名称:mongo-csharp-driver,代码行数:28,代码来源:BsonBinaryReaderTests.cs


示例12: CreateSeedData

    // Extra helper code
    static BsonDocument[] CreateSeedData()
    {
      BsonDocument seventies = new BsonDocument {
        { "Decade" , "1970s" },
        { "Artist" , "Debby Boone" },
        { "Title" , "You Light Up My Life" },
        { "WeeksAtOne" , 10 }
      };
 
      BsonDocument eighties = new BsonDocument {
        { "Decade" , "1980s" },
        { "Artist" , "Olivia Newton-John" },
        { "Title" , "Physical" },
        { "WeeksAtOne" , 10 }
      };
      
      BsonDocument nineties = new BsonDocument {
        { "Decade" , "1990s" },
        { "Artist" , "Mariah Carey" },
        { "Title" , "One Sweet Day" },
        { "WeeksAtOne" , 16 }
      };

      BsonDocument[] SeedData = { seventies, eighties, nineties };
      return SeedData;
    }
开发者ID:saurav111,项目名称:mongodb-driver-examples,代码行数:27,代码来源:CSharpSimpleExample.cs


示例13: Run

        public IEnumerable<BsonDocument> Run(MongoCollection<Rental> rentals)
        {
            var priceRange = new BsonDocument(
                "$subtract",
                new BsonArray
                {
                    "$Price",
                    new BsonDocument(
                        "$mod",
                        new BsonArray{"$Price",500}
                        )
                });
            var grouping =new BsonDocument(
                "$group",
                new BsonDocument
                {
                    {"_id",priceRange},
                    {"count",new BsonDocument("$sum",1)}
                });
            var sort=new BsonDocument(
                "$sort",
                new BsonDocument("_id",1)
                );

            var args=new AggregateArgs
            {
                Pipeline=new []{grouping,sort}
            };

            return rentals.Aggregate(args);
        }
开发者ID:nywebman,项目名称:MongoDBdotNet,代码行数:31,代码来源:QueryPriceDistribution.cs


示例14: AddUserEx

 /// <summary>
 ///     Adds a user to this database.
 /// </summary>
 /// <param name="user">The user.</param>
 public static void AddUserEx(MongoCollection Col, User user)
 {
     var document = Col.FindOneAs<BsonDocument>(Query.EQ("user", user.Username));
     if (document == null)
     {
         document = new BsonDocument("user", user.Username);
     }
     document["roles"] = user.roles;
     if (document.Contains("readOnly"))
     {
         document.Remove("readOnly");
     }
     //必须要Hash一下Password
     document["pwd"] = MongoUser.HashPassword(user.Username, user.Password);
     //OtherRole 必须放在Admin.system.users里面
     if (Col.Database.Name == MongoDbHelper.DATABASE_NAME_ADMIN)
     {
         document["otherDBRoles"] = user.otherDBRoles;
     }
     if (string.IsNullOrEmpty(user.Password))
     {
         document["userSource"] = user.userSource;
     }
     Col.Save(document);
 }
开发者ID:EricBlack,项目名称:MagicMongoDBTool,代码行数:29,代码来源:User.cs


示例15: TestNoCircularReference

        public void TestNoCircularReference()
        {
            var c2 = new C { X = 2 };
            var c1 = new C { X = 1, NestedDocument = c2 };

            var json = c1.ToJson();
            var expected = "{ 'X' : 1, 'NestedDocument' : { 'X' : 2, 'NestedDocument' : null, 'BsonArray' : { '_csharpnull' : true } }, 'BsonArray' : { '_csharpnull' : true } }".Replace("'", "\"");
            Assert.AreEqual(expected, json);

            var memoryStream = new MemoryStream();
            using (var writer = new BsonBinaryWriter(memoryStream))
            {
                BsonSerializer.Serialize(writer, c1);
                Assert.AreEqual(0, writer.SerializationDepth);
            }

            var document = new BsonDocument();
            using (var writer = new BsonDocumentWriter(document))
            {
                BsonSerializer.Serialize(writer, c1);
                Assert.AreEqual(0, writer.SerializationDepth);
            }

            var stringWriter = new StringWriter();
            using (var writer = new JsonWriter(stringWriter))
            {
                BsonSerializer.Serialize(writer, c1);
                Assert.AreEqual(0, writer.SerializationDepth);
            }
        }
开发者ID:Bogdan0x400,项目名称:mongo-csharp-driver,代码行数:30,代码来源:CircularReferencesTests.cs


示例16: TestInsertUpdateAndSaveWithElementNameStartingWithDollarSign

        public void TestInsertUpdateAndSaveWithElementNameStartingWithDollarSign()
        {
            // starting with version 2.5.2 the server got stricter about dollars in element names
            // so this test should only be run when testing against older servers
            var server = Configuration.TestServer;
            if (server.BuildInfo.Version < new Version(2, 6, 0))
            {
                var database = Configuration.TestDatabase;
                var collection = Configuration.TestCollection;
                collection.Drop();

                var document = new BsonDocument
                {
                    { "_id", 1 },
                    { "v", new BsonDocument("$x", 1) } // server doesn't allow "$" at top level
                };
                var insertOptions = new MongoInsertOptions { CheckElementNames = false };
                collection.Insert(document, insertOptions);
                document = collection.FindOne();
                Assert.AreEqual(1, document["v"]["$x"].AsInt32);

                document["v"]["$x"] = 2;
                var query = Query.EQ("_id", 1);
                var update = Update.Replace(document);
                var updateOptions = new MongoUpdateOptions { CheckElementNames = false };
                collection.Update(query, update, updateOptions);
                document = collection.FindOne();
                Assert.AreEqual(2, document["v"]["$x"].AsInt32);

                document["v"]["$x"] = 3;
                collection.Save(document, insertOptions);
                document = collection.FindOne();
                Assert.AreEqual(3, document["v"]["$x"].AsInt32);
            }
        }
开发者ID:Bogdan0x400,项目名称:mongo-csharp-driver,代码行数:35,代码来源:CSharp358Tests.cs


示例17: GetIndexName

        // static methods
        /// <summary>
        /// Gets the name of the index derived from the keys specification.
        /// </summary>
        /// <param name="keys">The keys specification.</param>
        /// <returns>The name of the index.</returns>
        public static string GetIndexName(BsonDocument keys)
        {
            Ensure.IsNotNull(keys, nameof(keys));
            var sb = new StringBuilder();

            foreach (var element in keys)
            {
                var value = element.Value;
                string direction;
                switch (value.BsonType)
                {
                    case BsonType.Double:
                    case BsonType.Int32:
                    case BsonType.Int64:
                        direction = value.ToInt32().ToString();
                        break;
                    case BsonType.String:
                        direction = value.ToString().Replace(' ', '_');
                        break;
                    default:
                        direction = "x";
                        break;
                }

                if (sb.Length > 0)
                {
                    sb.Append("_");
                }
                sb.Append(element.Name.Replace(' ', '_'));
                sb.Append("_");
                sb.Append(direction);
            }

            return sb.ToString();
        }
开发者ID:narutoswj,项目名称:mongo-csharp-driver,代码行数:41,代码来源:IndexNameHelper.cs


示例18: TestSetDocumentIdInt32

 public void TestSetDocumentIdInt32()
 {
     var document = new BsonDocument { { "x", "abc" } };
     ((IBsonIdProvider)BsonDocumentSerializer.Instance).SetDocumentId(document, 1); // 1 will be converted to a BsonInt32
     Assert.IsTrue(document["_id"].IsInt32);
     Assert.AreEqual(1, document["_id"].AsInt32);
 }
开发者ID:Bogdan0x400,项目名称:mongo-csharp-driver,代码行数:7,代码来源:CSharp446Tests.cs


示例19: DeleteAllData

 public async Task<bool> DeleteAllData(string CollectionName)
 {
     var collection = _database.GetCollection<BsonDocument>(CollectionName);
     var filter = new BsonDocument();
     var result = await collection.DeleteManyAsync(filter);
     return true;
 }
开发者ID:anwarminarso,项目名称:IDLake,代码行数:7,代码来源:DocumentDb.cs


示例20: UserInRole

 /// <summary>
 /// 查询角色下面所有用户
 /// </summary>
 /// <param name="UserRoleId"></param>
 /// <returns>返回所有用户</returns>
 public BsonArray UserInRole(ObjectId UserRoleId)
 {
     BsonDocument Query = new BsonDocument {
         { "UserRole", UserRoleId}
     };
     return GetUsersToArray(Query);
 }
开发者ID:Zane0816,项目名称:Mail-.Net,代码行数:12,代码来源:UserServer.cs



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# BsonElement类代码示例发布时间:2022-05-24
下一篇:
C# BsonClassMap类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap