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.

Hi!

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:

Short

db.companies.find({"offices.city":"Wonderland"})
//or
db.companies.find({"offices":{"$elemMatch":{"city":"Wonderland"}}})

Detailed

Take a simpler example:

{
  "offices":{ 
    "country": "Wonderland", 
    "name": "Alice's Office" 
   }
}

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

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

{
offices:[
   { city:"Wonderland",  name:"Alice's Office"}, 
   {doc2}, 
   {doc3}... 
   ]
}

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( {
   "offices":{
     "$elemMatch":{
      "city":"Wonderland"
       }
     }
})

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

could be used:

db.companies.find( {
   "offices":{
     "$elemMatch":{
      "city":"Wonderland",
      "state_code": "unknown"
       }
     }
})

Hope it helps.

1 Like

Thanks for the reply.

Just few mins back .Solved the Lab.