Wrong query for ObjectId

Hi

I’m using MongoDB driver for .Net Core 3.1 and there is a wrong query translation when I’m using lambda expression in the Project stage of the Aggregation pipeline

The model contains the following definition:

public class BaseValidity
{
    [BsonId]
    [BsonRepresentation(BsonType.ObjectId)]
    public string id { get; set; } = ObjectId.GenerateNewId().ToString();
}

And the query is:

var queryToExecute = _dataStreams.Aggregate()
    .Match(...)
    .Project(
        dataStream => new {
            validations = dataStream.episodes
            .Select(
                    episode => episode.validations
                .Where(validity => validity.id == baseValidityId).First()
            ).Where(validity => validity != null)
        } 
    );

But the output of the project stage is:

{ "$project" : {
  "validations" : {
    "$filter" : {
      "input" : {
        "$map" : {
          "input" : "$episodes",
          "as" : "episode",
          "in" : {
            "$arrayElemAt" : [
              { "$filter" : {
                "input" : "$$episode.validations",
                "as" : "validity",
                "cond" : **{ "$eq" : ["$$validity._id", "5f55fd057e29a07970048ce9"] }**
              }}, 0
            ]}
          }
        },
        "as" : "validity",
        "cond" : {
        "$ne" : [ "$$validity", null ]
      }
    }
  }
}}

it should be:

{ "$eq" : ["$$validity._id", ObjectId("5f55fd057e29a07970048ce9")] }

Is there any workaround for this issue?

I’m not sure what’s happening here but it looks like your function returns a “string” due to the “ToString” method which would indeed not result in an ObjectId but in the string representation of an ObjectId.

So maybe changing your get/set function into something like can help:

public ObjectId id { get; set; } = ObjectId.GenerateNewId();

Thank you @MaBeuLux88_xxx.

I don’t think it related to this line since when I used the Builder function it gives me the right $eq query.
I can send an example if needed

This returns a “string” right? So maybe you need something like new ObjectId(validity.id) or something like this in here?

I’m a Java guy so I can’t quite read what’s happening here but maybe something like this would fix the issue here?

.Where(validity => new ObjectId(validity.id) == new ObjectId(baseValidityId)).First()

It’s just a wild guess. If it’s not something like this, I don’t know, sorry :frowning:.