Skip to content

Instantly share code, notes, and snippets.

@dj-nitehawk
Last active March 13, 2020 13:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dj-nitehawk/bad7ea6fb9bf39d88e14f089236b2fb5 to your computer and use it in GitHub Desktop.
Save dj-nitehawk/bad7ea6fb9bf39d88e14f089236b2fb5 to your computer and use it in GitHub Desktop.
filter by month number using aggregation pipeline
using MongoDB.Driver;
using MongoDB.Entities;
using MongoDB.Entities.Core;
using System;
namespace StackOverFlow
{
public class Item : Entity
{
public DateTime DateOfCreation { get; set; }
}
public static class Program
{
private static void Main()
{
new DB("test", "localhost");
new[] {
new Item { DateOfCreation = new DateTime(2020,3,1,0,0,0,DateTimeKind.Utc) },
new Item { DateOfCreation = new DateTime(2020,3,2,0,0,0,DateTimeKind.Utc) },
new Item { DateOfCreation = new DateTime(2020,3,3,0,0,0,DateTimeKind.Utc) },
}.Save();
//https://dev.to/djnitehawk/overcoming-the-limitations-of-mongodb-c-driver-1110
var pipeline = new Template<Item>(@"
[{
$match: {
$expr: {
$eq: [
{ $month: '$<DateOfCreation>' },
<month_number>
]
}
}
}]")
.Path(i => i.DateOfCreation)
.Tag("month_number", "3");
var result = DB.Aggregate(pipeline).ToList();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment