简体   繁体   中英

How to get one or more array elements in MongoDB using a Linq expression

I'm working on a registry of people using MongoDB, C# dotnet and Linq for searches. This record has an array of the person's addresses, and I need to make a query by zip code that returns all the records that have the same zip code as the one searched for.

This is my class

    public class Retailer : Entity<Retailer>
    {
        public PersonType PersonType { get; private set; }

        public string CompanyName { get; private set; }

        public string TradingName { get; private set; }

        public IReadOnlyCollection<RetailerAddress> Adresses
        {
            get { return _adressesList.ToArray(); }
            set { _adressesList = value.ToList(); }
        }
.
.
.
Other methods omitted for brevity
.
.
.
    }

This is the object persisted in MongoDB

{
  "_id": "58beb0c5-950d-443b-943d-1580a5dfa223",
  "createdDate": "2022-07-13T17:27:50.7567299-03:00",
  "active": true,
  "PersonType": "PJ",
  "CompanyName": "Rotisseria Coma e Viva",
  "TradingName": "Coma e viva",
  "Adresses": [
    {
      "_id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
      "createdDate": "2022-07-13T17:27:50.745713-03:00",
      "active": true,
      "RetailerId": "58beb0c5-950d-443b-943d-1580a5dfa223",
      "Street": "Av Principal",
      "Number": "395",
      "Neighborhood": "Vila Soco",
      "Complement": "Em Frente A Farmácia",
      "City": "Santo André",
      "ZipCode": "09190000",
      "IbgeCityCode": "3547809",
      "State": "SP",
      "Country": "BR"
    },
    {
      "_id": "3fa85f64-5717-4562-b3fc-2c963f66afa7",
      "createdDate": "2022-07-13T17:27:50.745713-03:00",
      "active": false,
      "RetailerId": "58beb0c5-950d-443b-943d-1580a5dfa223",
      "Street": "Av Secondary",
      "Number": "395",
      "Neighborhood": "Vila Country",
      "Complement": "Ao lado do posto de gasolina",
      "City": "Pirapora",
      "ZipCode": "09190000",
      "IbgeCityCode": "3547809",
      "State": "SP",
      "Country": "BR"
    }
  ]
}

I want to get all people who are Active and who also have an Active address and a zip code equal to 09190000. I tried using a linq expression like this:

var result = await _retailerRepository.GetAsync(retailer => retailer.Active && retailer.Adresses.Where(address => address.ZipCode == zipCode));

But I get this error message: Operator '&&' cannot be applied to operands of type 'bool' and and 'IEnumerable'

How should I correct this message and return all records that contain the searched zip code?

var result = await _retailerRepository.GetAsync(retailer => retailer.Active && 零售商.Adresses.Any(address => address.ZipCode == zipCode));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM