Matching array fields

Introduction to MongoDB in Python

Donny Winston

Instructor

Array fields and equality

{'firstname': 'John',
 'surname': 'Bardeen',
 'prizes': [{
   'category': 'physics', 'year': '1956', 'share': '3',
   'motivation': ('"for their researches on semiconductors and their'
                  'discovery of the transistor effect"'),
   ...
  }, {
   'category': 'physics', 'year': '1972', 'share': '3',
   'motivation': ('"for their jointly developed theory of'
                  'superconductivity, usually called the BCS-theory"'),
   ...
  }],
 ...
}
db.laureates.count_documents({"prizes.category": "physics"})
206
206
Introduction to MongoDB in Python

Array fields and equality, simplified

# Imaginary extra field in John Bardeen's document:
{"nicknames": ["Johnny", "JSwitch", "JB", "Tc Johnny", "Bardy"]}
db.laureates.find({"nicknames": "JB"})
# different than {"nicknames": ["JB"]}

Introduction to MongoDB in Python

Array fields and operators

db.laureates.count_documents(
  {"prizes.category": "physics"})
206
db.laureates.count_documents(
  {"prizes.category": {"$ne": "physics"}})
716
db.laureates.count_documents({
    "prizes.category": {
        "$in": ["physics", "chemistry", "medicine"]}})
596
db.laureates.count_documents({
    "prizes.category": {
        "$nin": ["physics", "chemistry", "medicine"]}})
326
326
Introduction to MongoDB in Python

Enter $elemMatch

db.laureates.count_documents({
    "prizes": {
      "category": "physics", "share": "1"}})
0
db.laureates.count_documents({
    "prizes.category": "physics", "prizes.share": "1"})
48
db.laureates.count_documents({
    "prizes": {"$elemMatch": 
               {"category": "physics", "share": "1"}}})
47
db.laureates.count_documents({
    "prizes": {"$elemMatch": {
        "category": "physics",
        "share": "1",
        "year": {"$lt": "1945"},}}})
29
29
Introduction to MongoDB in Python

Onward and array-ward!

Introduction to MongoDB in Python

Preparing Video For Download...