Aggregation by date in Mongoba

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" .

, , , , . , . /, , . !

+3
1

, @chridam. !

, , - , .

, :

 var group = collection.Aggregate()
                       .Match(filter)
                       .Group(new BsonDocument { { "_id", new BsonDocument { { "month", new BsonDocument("$month", "$createddate.DateTime") }, { "day", new BsonDocument("$dayOfMonth", "$createddate.DateTime") }, { "year", new BsonDocument("$year", "$createddate.DateTime") } } }, { "count", new BsonDocument("$sum", 1) } })
                       .ToListAsync().Result;

. , :

var grouped = group.Select(g => BsonSerializer.Deserialize<RootObject>(g));

, :

public class Id
{
    public int month { get; set; }
    public int day { get; set; }
    public int year { get; set; }
}

public class RootObject
{
    public Id _id { get; set; }
    public int count { get; set; }
}

, . !:)

+3

Source: https://habr.com/ru/post/1613090/


All Articles