I'm trying to execute a Find
query on a IMongoCollection<CreditEntry>
, with a simple comparison of two integer properties. I am using the C# MongoDB.Driver 2.5.1 for this.
The CreditEntry
class contains these two integerfields: UsedCredits
and TotalCredits
and looks like this(simplified):
public class CreditEntry
{
public CreditEntry(string username, int totalCredits)
{
Id = Guid.NewGuid();
Username = username;
UsedCredits = 0;
TotalCredits = totalCredits;
}
public Guid Id { get; set; }
public string Username { get; set; }
public int UsedCredits { get; internal set; }
public int TotalCredits { get; internal set; }
public int Credits => TotalCredits - UsedCredits;
}
The code that should be able to find the user, that throws the System.ArgumentException
is(simplified):
string username = "user1";
var user = _collection.Find(c => c.Username == username &&
c.TotalCredits > c.UsedCredits).FirstOrDefault();
The exception looks like this:
{
"error":{
"code":"","message":"An error has occurred.","innererror":{
"message":"Unsupported filter: ({document}{TotalCredits} > {document}{UsedCredits}).","type":"System.ArgumentException"
I have made sure that there is a CreditEntry
for user1, where the TotalCredits
is more than the UsedCredits
, and that the collection exists.
If I execute this Find
query, it's working fine, but it lacks the integer comparison condition:
string username = "user1";
var user = _collection.Find(c => c.Username == username).FirstOrDefault();
So, my question is: Why can I not compare two integer properties of CreditEntry
in this Find query, and are there possibly other ways to achieve this?
EDIT: Why is a Func accepted as an input for the Find method, where you can compare an integer field i.e. TotalCredits
to a specific integer like i.e. 10, while comparing two fields isn't possible?
To illustrate this:
var user = _collection.Find(c => c.TotalCredits > 0 && c.Tenant == tenant).FirstOrDefault();
This query is completely valid, while comparing two fields isn't. Why does the one cause an exception while the other doesn't?