mongodb统计查询相关及csharp方面的应用收集
Example 1: Aggregation Framework Basic usage
var coll = localDb.GetCollection("examples");var match = new BsonDocument
{
{
"$match",
new BsonDocument
{
{"User", "Tom"}
}
}
};
var pipeline = new[] { match };
var result = coll.Aggregate(pipeline);
Console.WriteLine(result.ResultDocuments.Count());
var matchingExamples = result.ResultDocuments
.Select(BsonSerializer.Deserialize<ExampleData>)
.ToList();
foreach (var example in matchingExamples)
{
var message = string.Format("{0} - {1}", example.User, example.Count);
Console.WriteLine(message);
}
Another alternative is to use C#’s dynamic type. The following extension method uses JSON.net to convert a BsonDocument into a dynamic:
public static class MongoExtensions
{
public static dynamic ToDynamic(this BsonDocument doc)
{
var json = doc.ToJson();
dynamic obj = JToken.Parse(json);
return obj;
}
}
Here’s a way to convert all the result documents into dynamic objects:
var matchingExamples = result.ResultDocuments
.Select(x => x.ToDynamic())
.ToList();
Example 2: Multiple filters & comparison operators
This example filters the data with the following criteria:User: Tom
Count: >= 2
var match = new BsonDocument
{
{
"$match",
new BsonDocument
{
{"User", "Tom"},
{"Count", new BsonDocument
{
{
"$gte", 2
}
}}
}
}
};
The execution of this operation is identical to the first example:
var pipeline = new[] { match };
var result = coll.Aggregate(pipeline);
var matchingExamples = result.ResultDocuments
.Select(x => x.ToDynamic())
.ToList();
Also the result are as expected:
foreach (var example in matchingExamples)
{
var message = string.Format("{0} - {1}", example.User, example.Count);
Console.WriteLine(message);
}
Example 3: Multiple operations
In our first two examples, the pipeline was as simple as possible: It contained only one operation. This example will filter the data with the same exact criteria as the second example, but this time using two $match operations:User: Tom
Count: >= 2
var match = new BsonDocument
{
{
"$match",
new BsonDocument
{
{"User", "Tom"}
}
}
};
var match2 = new BsonDocument
{
{
"$match",
new BsonDocument
{
{"Count", new BsonDocument
{
{
"$gte", 2
}
}}
}
}
};
var pipeline = new[] { match, match2 };
Example 4: Group and sum
Thus far we’ve used the aggregation framework to just filter out the data. The true strength of the framework is its ability to run calculations on the documents. This example shows how we can calculate how many documents there are in the collection, grouped by the user. This is done using the $group-operator:var group = new BsonDocument
{
{ "$group",
new BsonDocument
{
{ "_id", new BsonDocument
{
{
"MyUser","$User"
}
}
},
{
"Count", new BsonDocument
{
{
"$sum", 1
}
}
}
}
}
};
The grouping key (in our case the User-field) is defined with the _id. The above example states that the grouping key has one field (“MyUser”) and the value for that field comes from the document’s User-field ($User). In the $group operation the other fields are aggregate functions. This example defines the field “Count” and adds 1 to it for every document that matches the group key (_id).
var pipeline = new[] { group };
var result = coll.Aggregate(pipeline);
var matchingExamples = result.ResultDocuments
.Select(x => x.ToDynamic())
.ToList();
foreach (var example in matchingExamples)
{
var message = string.Format("{0} - {1}", example._id.MyUser, example.Count);
Console.WriteLine(message);
}
Example 5: Group and sum by field
This example is similar to example 4. But instead of calculating the amount of documents, we calculate the sum of the Count-fields by the user:var group = new BsonDocument
{
{ "$group",
new BsonDocument
{
{ "_id", new BsonDocument
{
{
"MyUser","$User"
}
}
},
{
"Count", new BsonDocument
{
{
"$sum", "$Count"
}
}
}
}
}
};
The only change is that instead of adding 1, we add the value from the Count-field (“$Count”).
Example 6: Projections
This example shows how the $project operator can be used to change the format of the output. The grouping in example 5 works well, but to access the user’s name we currently have to point to the _id.MyUser-property. Let’s change this so that user’s name is available directly through UserName-property:var group = new BsonDocument
{
{ "$group",
new BsonDocument
{
{ "_id", new BsonDocument
{
{
"MyUser","$User"
}
}
},
{
"Count", new BsonDocument
{
{
"$sum", "$Count"
}
}
}
}
}
};
var project = new BsonDocument
{
{
"$project",
new BsonDocument
{
{"_id", 0},
{"UserName","$_id.MyUser"},
{"Count", 1},
}
}
};
var pipeline = new[] { group, project };
The code removes the _id –property from the output. It adds the UserName-property, which value is accessed from field _id.MyUser. The projection operations also states that the Count-value should stay as it is.
var matchingExamples = result.ResultDocuments
.Select(x => x.ToDynamic())
.ToList();
foreach (var example in matchingExamples)
{
var message = string.Format("{0} - {1}", example.UserName, example.Count);
Console.WriteLine(message);
}
Example 7: Group with multiple fields in the keys
For this example we add a new row into our document collection, leaving us with the following:{ “_id” : “1″, “User” : “Tom”, “Country” : “Finland”, “Count” : 1 }
{ “_id” : “2″, “User” : “Tom”, “Country” : “Finland”, “Count” : 3 }
{ “_id” : “3″, “User” : “Tom”, “Country” : “Finland”, “Count” : 2 }
{ “_id” : “4″, “User” : “Mary”, “Country” : “Sweden”, “Count” : 1 }
{ “_id” : “5″, “User” : “Mary”, “Country” : “Sweden”, “Count” : 7 }
{ “_id” : “6″, “User” : “Tom”, “Country” : “England”, “Count” : 3 }
This example shows how you can group the data by using multiple fields in the grouping key:
var group = new BsonDocument
{
{ "$group",
new BsonDocument
{
{ "_id", new BsonDocument
{
{ "MyUser","$User" },
{ "Country","$Country" },
}
},
{
"Count", new BsonDocument
{
{ "$sum", "$Count" }
}
}
}
}
};
var project = new BsonDocument
{
{
"$project",
new BsonDocument
{
{"_id", 0},
{"UserName","$_id.MyUser"},
{"Country", "$_id.Country"},
{"Count", 1},
}
}
};
var pipeline = new[] { group, project };
var result = coll.Aggregate(pipeline);
var matchingExamples = result.ResultDocuments
.Select(x => x.ToDynamic())
.ToList();
foreach (var example in matchingExamples)
{
var message = string.Format("{0} - {1} - {2}", example.UserName, example.Country, example.Count);
Console.WriteLine(message);
}
Example 8: Match, group and project
This example shows how you can combine many different pipeline operations. The data is first filtered ($match) by User=Tom, then grouped by the Country (“$group”) and finally the output is formatted into a readable format ($project).Match:
var match = new BsonDocument
{
{
"$match",
new BsonDocument
{
{"User", "Tom"}
}
}
};
Group:
var group = new BsonDocument
{
{ "$group",
new BsonDocument
{
{ "_id", new BsonDocument
{
{ "Country","$Country" },
}
},
{
"Count", new BsonDocument
{
{ "$sum", "$Count" }
}
}
}
}
};
Project:
var project = new BsonDocument
{
{
"$project",
new BsonDocument
{
{"_id", 0},
{"Country", "$_id.Country"},
{"Count", 1},
}
}
};
Result:
var pipeline = new[] { match, group, project };
var result = coll.Aggregate(pipeline);
var matchingExamples = result.ResultDocuments
.Select(x => x.ToDynamic())
.ToList();
foreach (var example in matchingExamples)
{
var message = string.Format("{0} - {1}", example.Country, example.Count);
Console.WriteLine(message);
}
c#一个简单完整的例子
public async Task<List<Counter>> GetList(Hashtable ht, int skip, int top)
{
var match = new BsonDocument
{
{
"$match",
new BsonDocument
{
{"_id" , new BsonDocument{{"$gt",0}}},
}
}
};
if (ht != null && ht.Count > 0)
{
if (ht.Contains("AgentId"))
{
Dictionary<string, object> el = new Dictionary<string, object>();
el.Add("AgentId", HQ.Job.Tools.StrHelper.ToInt32(ht["AgentId"].ToString()));
match.ElementAt(0).Value.AsBsonDocument.Add(el);
//match = match.ElementAt(1).ToBsonDocument().Add(el);
}
if (ht.Contains("StartDate"))
{
Dictionary<string, object> el = new Dictionary<string, object>();
Dictionary<string, object> subel = new Dictionary<string, object>();
subel.Add("$gte", HQ.Job.Tools.StrHelper.ToDateTime(ht["StartDate"].ToString()).AddHours(-8));
subel.Add("$lte", HQ.Job.Tools.StrHelper.ToDateTime(ht["EndDate"].ToString()).AddHours(-8));
el.Add("CreateTime", subel);
match.ElementAt(0).Value.AsBsonDocument.Add(el);
}
}
AggregateArgs args = new AggregateArgs();
var group = new BsonDocument
{
{ "$group",
new BsonDocument
{
{ "_id","$AgentId" },
{
"Count", new BsonDocument
{
{ "$sum", 1 }
}
}
}
}
};
var pipeline = new[] { match,group };
args.Pipeline = pipeline;
var result = await dal.QueryMongoGroupAsync<Entity.AgentReg>(args);
var list = new List<Counter>();
if (result != null && result.Count > 0)
{
foreach (BsonDocument item in result)
{
var myObj = BsonSerializer.Deserialize<Counter>(item);
list.Add(myObj);
}
}
return list;
}