Search code examples
mongodb.net-coreasp.net-core-mvcmongodb-.net-driverasp.net-core-webapi

How to query by object's object property with MongoDb Driver


I'm doing a .net core web api using mongodb driver to access my database.

I have this document's structure

{
"_id" : 1,
"ParticipantIdentities" : [
    {
        "ParticipantId" : 1,
        "Player" : {
            "AccountId" : 45678945,
            "AnotherProps" :"values"
            }
    }
    [Another arrays items]
  }

I want to fiter using object.ParticipantIdentities.Player.AccountId I tried this way

var filter = Builders<Match>.Filter.Where(e => e.ParticipantIdentities.Where(p => p.Player.AccountId == AccountId).Count() > 1);
var result = await _context.Matches.Find(filter).ToListAsync();

And it threw an exception saying the .Count() is not supported. I'm noob with mongodb queries yet.

Thanks in advance.


Solution

  • All you need to do is

    var filter = Builders<Match>.Filter.Eq("ParticipantIdentities.Player.AccountId", accountId);