Search code examples
c#mongodbbson

How to Pass MongoDB new Date() Function as Raw in Aggregation Query


I want to pass a MongoDB function (new Date()) as raw in an aggregation query from C#. I expect that in my MongoDB view, the result should look like this:

$and: [
  {
    create: {
      $lte: new Date()
    }
  }
]

However, when I try to use new BsonDocument, literal, BsonJavaScript, or BsonString, I always end up with something like:

$lte: "new Date()"

or

$lte: Code("new Date()")

Since my aggregation pipeline is quite large, I don't want to send everything as a JSON string. I simply want to have new Date() without quotation marks in my view.

Here’s a part of my current code:

var pipeline = new List<BsonDocument>
{
    new BsonDocument("$match", new BsonDocument("$and", new BsonArray
    {
        new BasicDBObject("create", new BsonDocument("$lte", new BsonDocument("new Date()"))),
        new BasicDBObject("end", new BsonDocument("$gte", new BsonDocument("new Date()")))
    }))
};

Can anyone help me adjust this so that new Date() is passed correctly?


Solution

  • No, i cannot use DateTime.Now, because it will be saved to view as constant date - as you can see in your own output.

    i used $$now function - it works as expected, so thanks Joe!