Home > Net >  How to implement MongoDB nested query in c# dotnet
How to implement MongoDB nested query in c# dotnet

Time:07-13

I have a MongoDB collection in the following format.


{
  "_id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
  "createdDate": "2022-07-09T20:25:38.8275833-03:00",
  "active": true,
  "PersonType": "PF",
  "CompanyName": "Teste Name",
  "TradingName": "Teste Nickname",
  "Documents": [
    {
      "_t": "Cpf",
      "type": "Cpf",
      "number": "49259564000"
    },
    {
      "_t": "RG",
      "type": "RG",
      "number": "925956408"
    }
  ]
}

When I try to get a document by Id or even the entire collection of documents, the Documents array always returns empty.

enter image description here

These are the repository query methods

        public virtual async Task<IReadOnlyCollection<T>> GetAllAsync(CancellationToken cancellationToken = default)
        {
            return await dbCollection.Find(filterBuilder.Empty).ToListAsync(cancellationToken);
        }

        public virtual async Task<T> GetAsync(Guid id, CancellationToken cancellationToken = default)
        {
            FilterDefinition<T> filter = filterBuilder.Eq(entity => entity.Id, id);

            return await dbCollection.Find(filter).FirstOrDefaultAsync(cancellationToken);
        }
  1. Why is the list of Documents returned not deserialized and returns empty?
  2. What is needed for the Documents list to be returned?

CodePudding user response:

The list of documents was being returned empty, due to the fact that in the Document class the Documents property was set private. After making the change according to the image, the list is returned with the populated documents.

enter image description here

  • Related