The code is really simple, I create a connection to the database and then retrieve a reference to collection that was selected in the interface from the user, then I use the Distinct() method of MongoCollection object, passing the name of the property you need, and Mongo gave you the distinct list of every value of that property. This permits me to populate the user interface with few lines of code.
Now it is time to think how to create a query to retrieve all the document with a certain level of logging and belonging to a list of possible loggerName.
In my software I usually use Castle Log4net Integration, this means that loggerName property is equals to the name of the class that issue the log and usually the user wants to see logs belonging to one or more class, something like:
all ERROR from classa or classb and severity ERROR. Mongo has a QueryBuilder helper class that makes easy to create such a query with a little help from intellisense and without the need to dirty your hand directly with JSONvar query = Query.And(
Query.EQ("level", "ERROR"),
Query.Or(
Query.EQ("loggerName", "classa"),
Query.EQ("loggerName", "classb")
)
);
复制代码Now I need to make this code dynamic, because I need to create a query that retrieve logs belonging to an unknown number of loggerName, such as “classa”, “classb” and “classc”, because user interface contains a CheckBoxList of every loggerName present into the database, and the user can choose any number of elements to search from, so I need to dynamically create the list of condition to create a dynamic query.List[I] mainQueries = new List[I]();
if (!String.IsNullOrWhiteSpace(cmbLevel.Text)) {
mainQueries.Add(Query.EQ("level", cmbLevel.Text));
}
if (cbList.CheckedIndices.Count > 0) {
List[I] listOfLoggerNameQueries = new List[I]();
foreach (Int32 index in cbList.CheckedIndices) {
String value = cbList.Items[index].ToString();
listOfLoggerNameQueries.Add(Query.EQ("loggerName", value));
}
mainQueries.Add(Query.Or(listOfLoggerNameQueries.ToArray()));
}
var finalQuery = Query.And(mainQueries.ToArray());
复制代码
|