Home > database >  C# MongoDriver Filter for Array length
C# MongoDriver Filter for Array length

Time:09-30

I want to find only documents where the "inventory"-Array has a length of 46 or less. But this doesn't seem to work, it returns false always, because it never finds a single document. How can I check how long an array of a document is?

And how would access them?

        {
            var User = userCollection.Find(x => x.id == userid && x.inventory.Length < 47).ToList();

            if (User.Count == 0) return false;
            else return true;
        }

CodePudding user response:

  1. There's something wrong in here userCollection.Find(x => x.id == userid && x.inventory.Length < 47).ToList(); we don't have enough code to assume the error, we ain't gonna guess it.
  2. You cannot Convert a var to a list
  3. You are using .Count method to a var & list

CodePudding user response:

try this:

var builder = Builders<User>.Filter;
var filter = builder.Eq(user=>user.Id,userid) & builder.Lt(user=>user.inventory.length,47);
var users = userCollection.Find(filter).ToList();

or for getting the count:

var usersCount = userCollection.Find(filter).CountDocuments();

CodePudding user response:

Well, the code I showed you did actually work. I just had a typo in it.

  • Related