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


C# BsonDocument类代码示例

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


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


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