Search code examples
c#mongodbasp.net-coremongodb-atlas-search

Aggregate Pipeline Atlas Search Stage using C#


I need to make this query using C#:

{
$search:{
{
  range:{
    path:"canvasAi.publication_date",
    gte:ISODate("2021-04-01T00:00:00Z"),
    lte:ISODate("2021-10-11T19:11:16.1928297Z")
  }
}
}
}

I have this so far:

var query = new JObject(
                    new JProperty("$search", new JObject(
                            new JProperty("range", new JObject(
                                    new JProperty("path", "canvasAi.publication_date"),
                                    new JProperty("gte", "ISODate('2021-04-01T00:00:00Z')"),
                                    new JProperty("lte", "ISODate('2021-10-11T19:11:16.1928297Z')")
                                ))
                        ))
                );

            var new_query = JsonConvert.SerializeObject(query);

var pipeline = new BsonDocument[]
            {
                BsonDocument.Parse(new_query)
            };
var result = collection.Aggregate<BsonDocument>(pipeline);

I keep getting the error from mongo that lte has to be a number, date.

I have the canvasAi.publication_date indexed using Atlas Search and the field is a string in the format give in the string above.

I have been trying for a few hours now and couldnt find a way to make this query.


Solution

  • looks like, the lte date is not recognized for some reason. Try using the BsonDocument form:

        var query = new BsonDocument
        {
            { 
                "$search",
                new BsonDocument
                {
                    {
                        "range",
                        new BsonDocument
                        {
                            { "path", "canvasAi.publication_date" },
                            { "gte", DateTime.Parse("2021-04-01T00:00:00Z") },
                            { "lte", DateTime.Parse("2021-10-11T19:11:16.1928297Z") }
                        }
                    }
                }
            }
        };