How to filter by day of week

I wanna filter documents by day of week using your C# library. I’m currently using IFindFluent but I guess it won’t be possible to do it with it and I have to build aggregation pipeline, how can I do this with C#?

I wanna get all documents where day of week != sunday

Hi @Konrad_N_A and welcome in the MongoDB Community :muscle: !

I’m the Java / Python guy here so I can’t really translate to C# but at least I got the query working:

db.coll.find({$expr: {$not: {$eq: [{$dayOfWeek: "$dateField"}, 1]}}})

Cheers,
Maxime.

1 Like

Hi, Konrad,

I’m one of the C# folks around these parts. We introduced support for DayOfWeek in our new LINQ3 provider. Internally we use the LINQ provider both for LINQ support and to translate lambdas in Fluent Find, Fluent Aggregate, and elsewhere into their MQL equivalents.

using System;
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Linq;

var settings = new MongoClientSettings { LinqProvider = LinqProvider.V3 };
var client = new MongoClient(settings);
var db = client.GetDatabase("test");
var coll = db.GetCollection<Appointment>("coll");

var find = coll.Find(x => x.Date.DayOfWeek != DayOfWeek.Sunday);
Console.WriteLine(find);
var query = coll.AsQueryable().Where(x => x.Date.DayOfWeek != DayOfWeek.Sunday);
Console.WriteLine(query);

class Appointment
{
    public ObjectId Id { get; set; }
    public DateTime Date { get; set; }
}

This will output the following MQL:

find({ "$expr" : { "$ne" : [{ "$subtract" : [{ "$dayOfWeek" : "$Date" }, 1] }, 0] } })
test.coll.Aggregate([{ "$match" : { "$expr" : { "$ne" : [{ "$subtract" : [{ "$dayOfWeek" : "$Date" }, 1] }, 0] } } }])

Note that LINQ3 was introduced in MongoDB .NET/C# Driver 2.14.0 (latest is 2.14.1) and is opt-in at the moment. More details can be found in our LINQ3 docs.

In summary, once you opt into LINQ3 you should be able to use DateTime.DayOfWeek in lambda expressions for LINQ, Fluent Find, Fluent Aggregate, and elsewhere and the driver will express this in MQL as $dayOfWeek.

Sincerely,
James

3 Likes

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.