The answer to this question goes in relation to the "Hygiene hypothesis" which pretty much states that the more we are exposed to the more tailored our immune response will be; thus those who are lacking exposures to certain things develop immunological issues such as allergies, asthma, eczema, etc. This in turn goes by the fact that as a fetus we are protected through our mother through sIgA and IgG* (mostly IgA during development). when we are born, depending on the route either through natural birth or C-section, we are exposed to those commensal microbiota of our mothers and that what is typically seen on us as adults along with everything else we encountered in our life's all through still being protected through our mother by breastfeeding and obtaining IgG/IgA protection (which is why its better to breastfeed and not go onto baby formula cause you are lacking that protection) until our immune system is built. With this our microbiota of our various body sites GU, UT, RT, etc are "sampled" and those that serve the harsh barriers without causing infection that life in a symbiotic relationship with us become our "friendly" bacteria. Now on the other end of the spectrum, which is also as more complicated and still unknown, when it comes to microbes and what causes us harm is already pre-determined in B and T cells that we contain even if activation though microbe contact hasnt even been seen before yet we are already protected (pretty much the genetics that we get from both our parents plays this role with genetic recombination in forming our antibodies and antigen receptor types, etc). through all of this and body continuously sampling the outside world through out immune system (macrophages, etc) and the competitive colonization of our good bacteria vs pathogens allows for not all microbes to be harmful. in order to be harmful we have to be suppressed in our immune system such as already sick, medications, drugs, genetics, environment, etc or ingest microbes such as that seen with food poisioning to be attacked by pathogenic bacteria.