I am writing a piece of functionality in which I need to group by date. This is how I am doing it now:
//Assuming this is my sample document in the collection
{
"_id" : ObjectId("56053d816518fd1b48e062f7"),
"memberid" : "7992bc31-c3c5-49e5-bc40-0a5ba41af0bd",
"sourceid" : NumberInt(3888),
"ispremium" : false,
"createddate" : {
"DateTime" : ISODate("2015-09-25T12:26:41.157+0000"),
"Ticks" : NumberLong(635787808011571008)
},
"details": {
//a large sub-document
}
}
Given the identifier of the participant, the start date and end date; I need to search for the collection matching these filters and group the results by date. In other words, the result I need to achieve is a list, for example (e.g. 12/10/2015 - count 5, 13/10/2015 - count is 2). StartDate and EndDate are DateTime types.
C # is the programming language I use, and currently, as I wrote:
var builder = Builders<MyCollection>.Filter;
var filter = builder.Eq(d => d.MemberId, memberId) & builder.Gte(d => d.CreatedDate, startDate) & builder.Lt(d => d.CreatedDate, endDate.AddDays(1));
var group = collection.Aggregate()
.Match(filter)
.Group(new BsonDocument { { "_id", "$createddate" }, { "count", new BsonDocument("$sum", 1) } })
.ToListAsync().Result;
Then I deserialize the result to a custom class ...
List<CustomAggregateResult> grouped = group.Select(g => BsonSerializer.Deserialize<CustomAggregateResult>(g)).OrderBy(g => g.Date).ToList();
, , . , , - , DateTime. , , , . , , . mongo :
db.mycollection.aggregate(
[
{
$group : {
_id : { month: { $month: "$createddate" }, day: { $dayOfMonth: "$createddate" }, year: { $year: "$createddate" } },
count: { $sum: 1 }
}
}
]
)
$match , . , , " BSON Date".
, , "" DateTime ( Date), . , . - , , ( -).
, datetime # ( , ):
[BsonDateTimeOptions(Representation = BsonType.Document)]
public DateTime CreatedDate {get; set; }
, "createddate" " " "Y-m-d" .
, , , , . , . /, , . !