mongo projection comparing enums as strings

19 views
Skip to first unread message

Vegar Vikan

unread,
Nov 16, 2017, 9:18:49ā€ÆAM11/16/17
to mongodb-user


I have a class calledĀ IdentityĀ with two properties:Ā TypeĀ andĀ Number. TheĀ TypeĀ property is an enum with theĀ [BsonRepresentation(BsonType.String)]Ā attribute set, so it's stored as strings instead of integers.

I now have a aggregation ending in a projection. In that projection, I have aĀ $filterĀ on an array of identities. That filter fails, and from what I can see, it fails because it tries to compare the stored string values to integer values.

I'll try to give an representation of my data and types:

Stored documents

class Customer
  [BsonRepresentation(BsonType.ObjectId)]      
  string Id;
  User[] Users;
  Items[] Items;
end;

class User
  Identity Identity;
end;

class Identity
  [BsonRepresentation(BsonType.String)]
  IdentityType IdentityType;
  string IdentityNumber;
end;

class Item
  [BsonRepresentation(BsonType.ObjectId)]      
  string Id;
end;

My aggregation

_collection.Aggregate()
  .Match(Builders<Customer>.Filter.In("Items.Id", ["id1", "id2"]))
  .Unwind<UnwindedCustomer>("Items")
  .Match(Builders<UnwindedCustomer>.Filter.In("Items.Id",  ["id1", "id2"]))
  .Project(doc => new
  {
    Id = doc.Items.Id,
    CustomerId = doc.Id,
    UserIsCustomer = doc.Users.Where(user =>
      user.Identity.IdentityNumber == "123" &&
      user.Identity.IdentityType == IdentityType.SomeType)
  });

So I'm looking for some specific items, and for those items, I want to know which customer they belongs to, and if the given user is a listed user of that customer.

If I render the last stage of the projection, I get something like

{ "$project" : 
  { 
    "Id" : "$Items.Id", 
    "CustomerId" : "$_id", 
    "UserIsCustomer" : 
    { "$filter" : 
        { 
          "input" : "$Users", 
          "as" : "user", 
          "cond" : { "$and" : [
            { "$eq" : ["$$user.Identity.IdentityNumber", "123"] }, 
            { "$eq" : ["$$user.Identity.IdentityType", 1] }
          ] } 
    } }, 
    "_id" : 0 
  } 
}

Why isn't theĀ IdentityTypeĀ rendered as a string?

Vegar Vikan

unread,
Nov 16, 2017, 9:19:35ā€ÆAM11/16/17
to mongodb-user
oops sorry - Guess this one should be in the `mongodb-csharp`-group...
Reply all
Reply to author
Forward
0 new messages