Array Operators and Projection

Chapter 4 .Lab : Array Operators and Projection

How many companies in the sample_training.companies collection have offices in the city of Seattle?

I don’t see any field like city or address in the sample_training.companies collection.


That’s strange, would you share a screenshot of your query?

Just to clear it, sample_training.companies is the namespace. It means:

  • db: sample_training,
  • collection: companies

tried with filter option in atlas as {“city” : “Seattle”}
{“city” : “seattle”}
{"address " : “city of seattle”}.

FYI: checked in companies collection only. files office exists which is array. not sure how to solve without finding “city of Seattle”.

Hi @Venkata_Geetha_Devi_Mandali. Here are some ideas that you may test :slight_smile:




Take a simpler example:

    "country": "Wonderland", 
    "name": "Alice's Office" 

Here we use the “dot” trick shown above {"":"Wonderland"}

Now, what if this is the value of offices is:

   { city:"Wonderland",  name:"Alice's Office"}, 

MongoDB is clever. Finds “alert Array” (the type), and traverses the array: it testes the equality for each element in the array.

Hence, it will find any sub-document where Alice lives in Wonderland (or not, if it’s not there).

Now you can reshape the query.

In the course $elemMatch is taught, and indeed this query could be used:

db.companies.find( {

This is specially useful if more than one condition is needed:

could be used:

db.companies.find( {
      "state_code": "unknown"

Hope it helps.

1 Like

Thanks for the reply.

Just few mins back .Solved the Lab.