本文整理汇总了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);
}
}
示例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;
}
示例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);
}
示例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);
}
示例5: ExplainOperationTests
public ExplainOperationTests()
{
_command = new BsonDocument
{
{ "count", _collectionNamespace.CollectionName }
};
}
示例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);
}
示例7: BulkWriteError
// constructors
internal BulkWriteError(int index, int code, string message, BsonDocument details)
{
_code = code;
_details = details;
_index = index;
_message = message;
}
示例8: BsonDocumentReader
public BsonDocumentReader(
BsonDocument document
)
{
context = new BsonDocumentReaderContext(null, ContextType.TopLevel, document);
currentValue = document;
}
示例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<"">);
}
示例10: CountFilteredWithBsonDocument
public async Task CountFilteredWithBsonDocument()
{
BsonDocument filter = new BsonDocument("_id", "050305007");
long count = await SchoolContext.StudentsAsBson.CountAsync(filter);
count.Should().Be(1);
}
示例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);
}
}
示例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;
}
示例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);
}
示例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);
}
示例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);
}
}