本文整理汇总了C#中IMongoCollection.Find方法的典型用法代码示例。如果您正苦于以下问题:C# IMongoCollection.Find方法的具体用法?C# IMongoCollection.Find怎么用?C# IMongoCollection.Find使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类IMongoCollection
的用法示例。
在下文中一共展示了IMongoCollection.Find方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: FillData
private static async Task FillData(
dynamic profile,
SqlConnection connection,
IMongoCollection<BsonDocument> threadCollection,
IMongoCollection<BsonDocument> threadProfiles)
{
var tags = connection.Query<string>(SqlQueryFactory.Instance.Get("get_thread_tags"), new { ThreadId = profile.Id });
var key = Builders<BsonDocument>.Filter.Eq("id", (profile.Id as string).Trim());
var match = await threadCollection.Find(key).Project("{url: 1, messages: 1, _id: 0}").SingleOrDefaultAsync();
var updateAction = Builders<BsonDocument>.Update
.Set("create_on", (DateTime)profile.CreateOn)
.Set("category", profile.Category as string)
.Set("title", profile.Title as string)
.Set("type", profile.Type as string);
if (match != null)
{
var html = match.GetValue("messages")
.AsBsonArray
.FirstOrDefault()
.AsBsonDocument
.GetValue("body").AsString;
var document = new HtmlAgilityPack.HtmlDocument();
document.LoadHtml(html);
var text = document.DocumentNode.InnerText;
var excerpt = text.Substring(0, Math.Min(256, text.Length));
updateAction = updateAction.Set("url", match.GetValue("url").AsString)
.Set("excerpt", excerpt);
}
if (tags != null)
{
var tagArray = new BsonArray(tags.Select(m => m.ToLower()).ToList());
updateAction = updateAction.Set("tags", tagArray);
}
await threadProfiles.UpdateOneAsync("{'_id': '" + (profile.Id as string).Trim() + "'}",
updateAction,
new UpdateOptions { IsUpsert = true });
}
示例2: GetDocuments
protected virtual IEnumerable<BsonDocument> GetDocuments(IMongoCollection<BsonDocument> collection)
{
var query = Filter();
var find = query != null
? collection.Find(query)
: collection.Find(Builders<BsonDocument>.Filter.Empty);
return find.ToList();
}
示例3: loadColors
public void loadColors(IMongoCollection<board_item> coll, string boardName)
{
List<board_item> colors = coll.Find(brd => brd.Type == "Color" && brd.Board_Name == boardName)
.ToListAsync()
.Result;
int i = 1;
foreach (board_item color in colors)
{
if (i == 1)
{
colorPlace1.ImageUrl = color.Image_Link;
i++;
colorPlace2.ImageUrl = "https://upload.wikimedia.org/wikipedia/commons/thumb/7/70/Solid_white.svg/2000px-Solid_white.svg.png";
}
else if (i == 2)
{
colorPlace2.ImageUrl = color.Image_Link;
i++;
colorPlace3.ImageUrl = "https://upload.wikimedia.org/wikipedia/commons/thumb/7/70/Solid_white.svg/2000px-Solid_white.svg.png";
}
else if (i == 3)
{
colorPlace3.ImageUrl = color.Image_Link;
}
}
}
示例4: NewMethod
private async void NewMethod(IMongoCollection<BsonDocument> collection)
{
var list = await collection.Find(_ => true).ToListAsync();
foreach (var item in list)
{
}
}
开发者ID:thEpisode,项目名称:Sistema-de-gestion-de-requerimientos-konrad-lorenz,代码行数:8,代码来源:HomeController.cs
示例5: GetDocuments
protected virtual IEnumerable<BsonDocument> GetDocuments(IMongoCollection<BsonDocument> collection)
{
var query = Filter();
if (query != null)
{
return query.ToList();
}
return collection.Find(Builders<BsonDocument>.Filter.Empty).ToList();
}
示例6: FindCustomer
static async Task FindCustomer(IMongoCollection<Customer> collection)
{
//creates a filter to find Bson Document
var filter = Builders<Customer>.Filter.Eq(c => c.FirstName, "John");
//runs the query to find it
var query = await collection.Find(filter).ToListAsync();
//gets the customer
var customer = query.FirstOrDefault();
//displays the customer using C# 6.0 string formatter
Console.WriteLine($"Customer {customer.FirstName} {customer.LastName} is found!");
}
示例7: FindPhone
/// <summary>
/// Finds phones in database using a name.
/// </summary>
/// <returns>The phone.</returns>
/// <param name="collection">Collection.</param>
private static async Task FindPhone(IMongoCollection<PhoneBookRecord> collection)
{
Console.WriteLine("Enter a name");
string name = Console.ReadLine();
var filter = Builders<PhoneBookRecord>.Filter.Eq("Name", name);
var names = await collection.Find(filter).ToListAsync();
foreach (var n in names)
{
Console.WriteLine(n.Phone);
}
}
示例8: LoadUids
private static async Task<List<int>> LoadUids(IMongoCollection<BsonDocument> collection, int uidKey)
{
var uid0 = uidKey * 0x1000000;
var uid1 = uid0 + 0xFFFFFF;
var uids = new List<int>();
await collection
.Find(Builders<BsonDocument>.Filter.Gte("_id", uid0) &
Builders<BsonDocument>.Filter.Lte("_id", uid1))
.Project(Builders<BsonDocument>.Projection.Include("_id"))
.ForEachAsync(x => uids.Add((int)x["_id"]));
return uids;
}
示例9: GetAllDrinks
private static void GetAllDrinks(IMongoCollection<EnergyDrink> collection)
{
Console.Clear();
var rest = collection.Find(_ => true);
foreach (var item in rest.ToListAsync().Result)
{
Console.WriteLine("Name: {0} => Price: {1}", item.Name, item.Price);
}
Console.WriteLine("\nPress any key to continue..");
Console.ReadLine();
}
示例10: findDocuments
static async Task findDocuments(IMongoCollection<student> collection, FilterDefinition<student> searchFilter)
{
//Option 1: for iterting over many documents on the server.
Console.WriteLine("--------------------------------------------------------------------");
///using (var cursor = await collection.Find(searchFilter).Sort("{student_id:1, scores.type:1}").ToCursorAsync())
using (var cursor = await collection.Find(searchFilter).ToCursorAsync())
{
using (StreamWriter w = File.AppendText("c:\\data\\hw31.txt"))
{
while (await cursor.MoveNextAsync()) //iterate over each batch
{
foreach (var doc in cursor.Current)
{
double minHWScore = 100.0;
///string text = i + " :=> sid: " + doc.student_id + ":" + doc.scores.ToString();
List<studentscore> thisStudentScores = doc.scores.ToList();
foreach (studentscore s in thisStudentScores)
{
if (s.type.Equals("homework"))
{
if (s.score < minHWScore)
{
minHWScore = s.score;
}
}
}
studentscore[] newScores = thisStudentScores.Where((x) => x.score != minHWScore).ToArray<studentscore>();
doc.scores = newScores.ToArray<studentscore>();
var filter = Builders<student>.Filter.Eq("Id", doc.Id);
await collection.ReplaceOneAsync(filter, doc);
Console.WriteLine(doc.ToString());
w.WriteLine(doc.ToString());
/**
if (i % 4 == 0)
{
Console.WriteLine("lowest score for " + doc.student_id + " is " + doc.score);
w.WriteLine("lowest score for " + doc.student_id + " is " + doc.score);
await collection.DeleteOneAsync(a => a.Id == doc.Id);
}
i++;
**/
}
}
}
}
}
示例11: AtualizarRegistro
private static bool AtualizarRegistro(IMongoCollection<Cidade> cidades)
{
// Encontra o registro
Cidade atualizaCidade = cidades.Find(c => c.Nome == "Charles Lomboni").ToList().First();
// Atualiza o valor do registro
atualizaCidade.Estado = "RJ";
// Atualiza no mongo
ReplaceOneResult estadoReplace = cidades.ReplaceOne(c => c._id == atualizaCidade._id, atualizaCidade);
// Se tiver encontrado e atualizado será maior que zero
return estadoReplace.ModifiedCount > 0;
}
示例12: FindByName
private static void FindByName(IMongoCollection<Note> collection)
{
Console.Write("Введите имя для поиска: ");
string name = Console.ReadLine();
var list = collection.Find(new BsonDocument()).ToList();
int count = 0;
foreach (var node in list)
if (node.Name == name)
{
++count;
Console.WriteLine($"Его номер ({count}): {node.Number}");
}
if (count == 0)
Console.WriteLine("Ничего не найдено");
}
示例13: AddNewNote
private static void AddNewNote(IMongoCollection<Note> collection)
{
Console.Write("Введите номер: ");
string newNumber = Console.ReadLine();
Console.Write("Введите имя: ");
string newName = Console.ReadLine();
var list = collection.Find(new BsonDocument()).ToList();
foreach (var node in list)
if (node.Number == newNumber)
{
Console.WriteLine("Такой номер уже записан под именем " + node.Name);
return;
}
collection.InsertOne(new Note { Name = newName, Number = newNumber });
Console.WriteLine("Запись добавлена");
}
示例14: Start
public override async void Start()
{
base.OnceTime = true;
// Standard URI format: mongodb://[dbuser:[email protected]]host:port/dbname
String uri = "mongodb://[petahost2.ns.co.th:27017/travox-mbos";
var client = new MongoClient(uri);
db = client.GetDatabase("travox-mbos");
oAuth = db.GetCollection<BsonDocument>("oAuth");
await oAuth.Find(filter).ForEachAsync(song =>
Console.WriteLine("In the {0}, {1} by {2} topped the charts for {3} straight weeks",
song["Decade"], song["Title"], song["Artist"], song["WeeksAtOne"])
);
base.Start();
}
示例15: FindAllAndPrint
private static void FindAllAndPrint(IMongoCollection<Category> coll, string name)
{
var results = coll.Find(t => t.Name == name)
.Limit(10)
.ToListAsync().Result;
Console.Write("List of categories\n**************************\n");
foreach (var result in results)
{
Console.WriteLine("Name : " + result.Name);
Console.WriteLine("Description : " + result.Description);
Console.WriteLine();
}
foreach (var expensse in results.SelectMany(t => t.Expenses))
{
Console.WriteLine("Amount : " + expensse.Amount);
Console.WriteLine("Date : " + expensse.Date);
Console.WriteLine("Transaction : " + expensse.Transaction);
}
}