skip to Main Content

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?

2

Answers


  1. Chosen as BEST ANSWER

    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!


  2. As mentioned in the comments, you should use a c# DateTime class. You can see result if you render the pipeline:

            var pipeline = new EmptyPipelineDefinition<BsonDocument>()
                .Match(new BsonDocument("$and", new BsonArray
                {
                    new BsonDocument("create", DateTime.UtcNow),
                    new BsonDocument("end", DateTime.UtcNow)
                }));
    
            // render for driver version 3.0:
            var registry = BsonSerializer.SerializerRegistry;
            var rendered = pipeline.Render(new RenderArgs<BsonDocument>
            {
                SerializerRegistry = registry,
                DocumentSerializer = registry.GetSerializer<BsonDocument>()
            })
                .Documents
                .Single()
                .ToString();
    

    Output:

    {
        "$match": {
            "$and": [
                {
                    "create": {
                        "$lte": {
                            "$date": "2024-12-09T20:19:34.97Z"
                        }
                    }
                },
                {
                    "end": {
                        "$gte": {
                            "$date": "2024-12-09T20:19:34.979Z"
                        }
                    }
                }
            ]
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search