本文整理汇总了C#中MongoCollection.FindOne方法的典型用法代码示例。如果您正苦于以下问题:C# MongoCollection.FindOne方法的具体用法?C# MongoCollection.FindOne怎么用?C# MongoCollection.FindOne使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类MongoCollection
的用法示例。
在下文中一共展示了MongoCollection.FindOne方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: FindOne
public IDictionary<string, object> FindOne(MongoCollection<BsonDocument> collection, SimpleExpression criteria)
{
if (criteria == null)
return collection.FindOne().ToSimpleDictionary();
var mongoQuery = _expressionFormatter.Format(criteria);
var results = collection.FindOne(mongoQuery);
return results.ToSimpleDictionary();
}
示例2: Page_Load
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
if (String.IsNullOrWhiteSpace(txtUsername.Text) || String.IsNullOrWhiteSpace(txtPassword.Text))
{
lblLoginError.Text = "Missing username or password";
}
else
{
string connectionstring = "mongodb://localhost";
MongoServer server = MongoServer.Create(connectionstring);
MongoDatabase pq = server.GetDatabase("pq");
MongoCollection<BsonDocument> users = new MongoCollection<BsonDocument>(pq, new MongoCollectionSettings<BsonDocument>(pq, "users"));
var query = Query.EQ("username", txtUsername.Text);
BsonDocument u = users.FindOne(query);
if (u == null)
{
lblLoginError.Text = "Error: No user found";
server.Disconnect();
}
else if (u.Contains("username") && u.Contains("password"))
{
if (u["username"] != txtUsername.Text || u["password"] != txtPassword.Text)
{
lblLoginError.Text = "Error: Invalid user/password combination";
server.Disconnect();
//Response.End();
}
else
{
if (u.Contains("user_id"))
{
Session.Add("username", u["username"].ToString());
Session.Add("user_id", u["_id"].ToString());
lblLoginError.Text = "Login Successful!";
server.Disconnect();
Response.Redirect("Default.aspx");
}
else
{
lblLoginError.Text = "Unknown login error";
server.Disconnect();
//Response.End();
}
}
}
else
{
lblLoginError.Text = "Error: User not found";
server.Disconnect();
//Response.End();
}
//Response.End();
}
}
}
示例3: AddConfigDocument
private void AddConfigDocument(MongoCollection<BsonDocument> collection, string type, string value)
{
BsonDocument doc = new BsonDocument
{
{"Type",type},
{"Name",value}
};
//var query = new QueryDocument("Name", doc.GetElement("Name").Value.ToString());
var query = new QueryDocument("Name", value);
var findResult = collection.FindOne(query);
if(findResult==null)
collection.Insert(doc);
}
示例4: Page_Load
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Params.HasKeys())
{
try
{
string id = Request.Params.GetValues("id")[0].ToString();
if (id == null)
{
lblTitle.Text = "Error no: id given!";
}
else
{
string connectionstring = "mongodb://localhost";
MongoServer server = MongoServer.Create(connectionstring);
MongoDatabase pq = server.GetDatabase("pq");
MongoCollection<BsonDocument> images = new MongoCollection<BsonDocument>(pq, new MongoCollectionSettings<BsonDocument>(pq, "images"));
var q = Query.EQ("_id", new ObjectId(id));
BsonDocument image = images.FindOne(q);
if (image.Contains("title"))
{
lblTitle.Text = image["title"].ToString();
}
lblImageId.Text = image["_id"].ToString();
lblOwner.Text = image["owner"].ToString();
lblMime.Text = image["mime"].ToString();
lblSize.Text = image["size"].ToString();
string url = "http://localhost:8085/?id=" + image["_id"].ToString();
if (image["height"] > 400 || image["width"] > 400)
{
url += "&width=400&height=400";
}
imgImage.ImageUrl = url;
server.Disconnect();
}
}
catch (Exception ex)
{
lblTitle.Text = "Error no: id given!";
}
}
}
示例5: CheckLocExists
private string CheckLocExists(double latitude, double longitude, MongoCollection<Location> locations, out string statusMessage)
{
statusMessage = null;
string locationID = null;
try
{
if (locations.Count() > 0)
{
var locationQuery = Query.And(Query.EQ("longitude", longitude), Query.EQ("latitude", latitude));
var existedLocation = locations.FindOne(locationQuery);
if (existedLocation != null)
locationID = (existedLocation as Location).locationID;
//File.WriteAllText(@"C:\locations.txt", "(current locationQuery) = " + locationQuery.ToJson() + " (current existedLocation) = " + existedLocation.ToJson() + " locationID = " + locationID + " " + DateTime.Now);
}
}
catch (Exception e)
{
locationID = null;
statusMessage = "An exception has occured in CheckLocExists method. " + e.Message;
}
return locationID;
}
示例6: CheckUserExists
private string CheckUserExists(string userName, MongoCollection<UserLegitimation> users, out string statusMessage)
{
statusMessage = null;
string userID = null;
try
{
if (users.Count() > 0)
{
var userQuery = Query.EQ("userName", userName);
var existedUser = users.FindOne(userQuery);
if (existedUser != null)
userID = (existedUser as UserLegitimation).userID;
}
}
catch (Exception e)
{
userID = null;
statusMessage = "An exception has occured in CheckUserExists method. " + e.Message;
}
return userID;
}
示例7: Get
protected object Get(MongoCollection<object> collection, Guid id)
{
return collection.FindOne(Query.EQ("_id", id));
}
示例8: RemoveMatchingAttributes
private void RemoveMatchingAttributes(MongoCollection<BsonDocument> data, string serviceName, string[] attributes)
{
var srvToRemoveAttr = data.FindOne(MongoQueryBuilder.EQ(ServiceNameFieldName, serviceName));
var srvToRemoveAttrData = srvToRemoveAttr[ServiceDataFieldName];
if (srvToRemoveAttrData != null) {
var srvToRemoveAttrDataArr = srvToRemoveAttrData.AsBsonArray;
if (srvToRemoveAttrDataArr != null && srvToRemoveAttrDataArr.Count > 0) {
data.Update(
MongoQueryBuilder.And(
MongoQueryBuilder.EQ(ServiceNameFieldName, serviceName)
),
MongoUpdateBuilder.Pull(
ServiceDataFieldName,
MongoQueryBuilder.In(
AttributeFieldName, new BsonArray(attributes)
)
)
);
}
}
}
示例9: ListenerCallback
private void ListenerCallback(IAsyncResult ar)
{
_busy.WaitOne();
HttpListenerContext context = null;
try
{
try
{ context = _listener.EndGetContext(ar); }
catch (HttpListenerException)
{ return; }
if (_stop.WaitOne(0, false))
return;
Console.WriteLine("{0} {1}", context.Request.HttpMethod, context.Request.RawUrl);
context.Response.SendChunked = true;
string connectionstring = "mongodb://localhost";
string id = context.Request.QueryString.Get("id");
StreamWriter sw;
if (String.IsNullOrWhiteSpace(id))
{
sw = new StreamWriter(context.Response.OutputStream);
sw.WriteLine("Accept-Ranges: bytes");
sw.WriteLine("Content-Length: 0");
sw.WriteLine("Content-Type: text/plain");
sw.WriteLine();
context.Response.Close();
throw new ArgumentException("No id!");
}
MongoServer server = MongoServer.Create(connectionstring);
server.Connect();
MongoDatabase pq = server.GetDatabase("pq");
MongoCollection<BsonDocument> images = new MongoCollection<BsonDocument>(pq, new MongoCollectionSettings<BsonDocument>(pq, "images"));
List<IMongoQuery> mqconstraints = new List<IMongoQuery>();
mqconstraints.Add(Query.EQ("_id", new ObjectId(id)));
// Check for other params
int width = -1;
int height = -1;
int cropx1 = -1;
int cropy1 = -1;
int cropx2 = -1;
int cropy2 = -1;
bool constrain = false;
bool cropPossible = false;
bool resizePossible = false;
try
{
width = Convert.ToInt32(String.IsNullOrWhiteSpace(context.Request.QueryString.Get("width")) ? "-1" : context.Request.QueryString.Get("width"));
height = Convert.ToInt32(String.IsNullOrWhiteSpace(context.Request.QueryString.Get("height")) ? "-1" : context.Request.QueryString.Get("height"));
constrain = (context.Request.QueryString.Get("constrain") == "0" ? false : true);
cropx1 = Convert.ToInt32(String.IsNullOrWhiteSpace(context.Request.QueryString.Get("cropx1")) ? "-1" : context.Request.QueryString.Get("cropx1"));
cropy1 = Convert.ToInt32(String.IsNullOrWhiteSpace(context.Request.QueryString.Get("cropy1")) ? "-1" : context.Request.QueryString.Get("cropy1"));
cropx2 = Convert.ToInt32(String.IsNullOrWhiteSpace(context.Request.QueryString.Get("cropx2")) ? "-1" : context.Request.QueryString.Get("cropx2"));
cropy2 = Convert.ToInt32(String.IsNullOrWhiteSpace(context.Request.QueryString.Get("cropy2")) ? "-1" : context.Request.QueryString.Get("cropy2"));
if (cropx1 >= 0 && cropy1 >= 0 && cropx2 >= 0 && cropy2 >= 0)
{
cropPossible = true;
mqconstraints.Add(Query.EQ("cropx1", cropx1));
mqconstraints.Add(Query.EQ("cropy1", cropy1));
mqconstraints.Add(Query.EQ("cropx2", cropx2));
mqconstraints.Add(Query.EQ("cropy2", cropy2));
}
if (width > 0 && height > 0)
{
resizePossible = true;
mqconstraints.Add(Query.EQ("width", width));
mqconstraints.Add(Query.EQ("height", height));
}
if (cropPossible || resizePossible)
{
mqconstraints.RemoveAt(0);
}
}
catch (Exception exc)
{
sw = new StreamWriter(context.Response.OutputStream);
sw.WriteLine("Accept-Ranges: bytes");
sw.WriteLine("Content-Length: 0");
sw.WriteLine("Content-Type: text/plain");
sw.WriteLine();
Console.WriteLine("Constraint Error");
context.Response.Close();
server.Disconnect();
throw exc;
}
if (server.State == MongoServerState.Disconnected)
{
throw new InvalidDataException("Invalid data!");
}
mqconstraints.Add(Query.EQ("parent", new ObjectId(id)));
BsonDocument doc = images.FindOne(Query.And(mqconstraints.ToArray()));
if (doc == null)
{
doc = images.FindOne(Query.EQ("_id", new ObjectId(id)));
if (doc==null)
//.........这里部分代码省略.........
示例10: UpdateUsingAtomicIncrement
/// <summary>
/// Demoes Updates a single field using an atomic Increment ($inc) operator.
/// </summary>
/// <param name="orders">The orders.</param>
private static void UpdateUsingAtomicIncrement(MongoCollection<Order> orders)
{
Console.WriteLine("\n\n======= Update Document using Increment =======");
var query = Query.EQ("CustomerName", "Daffy Duck");
Console.WriteLine("Before Update: " + orders.FindOne(query));
// Add 2000 to order amount on document matching selector.
orders.Update(query, Update.Inc( "OrderAmount", 2000 ));
Console.WriteLine("After Update: " + orders.FindOne(query));
}
示例11: UpdateDocument
/// <summary>
/// Demo of Updating a document.
/// </summary>
/// <param name="orders">The orders.</param>
private static void UpdateDocument(MongoCollection<Order> orders)
{
Console.WriteLine("\n\n======= Update Documents =======");
var query = Query.EQ( "CustomerName", "Daffy Duck" );
var orderToUpdate = orders.FindOne( query );
Console.WriteLine("Before Update: " + orderToUpdate);
// I'm in the money!
orderToUpdate.OrderAmount = 1000000.00;
// Update Daffy's account before Hasaan finds him.
orders.Save(orderToUpdate);
Console.WriteLine("After Update: " + orders.FindOne(query));
}