Introduction to MongoDB in Python
Donny Winston
Instructor
{'_id': ObjectId('5b9ac94ff35b63cf5231ccb1'),
'born': '1845-03-27',
'bornCity': 'Lennep (now Remscheid)',
'bornCountry': 'Prussia (now Germany)',
'bornCountryCode': 'DE',
'died': '1923-02-10',
'diedCity': 'Munich',
'diedCountry': 'Germany',
'diedCountryCode': 'DE',
'firstname': 'Wilhelm Conrad',
'gender': 'male',
'id': '1',
'prizes': [{'affiliations': [{'city': 'Munich',
'country': 'Germany',
'name': 'Munich University'}],
'category': 'physics',
'motivation': '"in recognition of the extraordinary services '
'he has rendered by the discovery of the '
'remarkable rays subsequently named after him"',
'share': '1',
'year': '1901'}],
'surname': 'Röntgen'}
Count documents by providing a filter document to match.
filter_doc = {
'born': '1845-03-27',
'diedCountry': 'Germany',
'gender': 'male',
'surname': 'Röntgen'
}
db.laureates.count_documents(filter_doc)
1
db.laureates.count_documents({'gender': 'female'})
48
db.laureates.count_documents({'diedCountry': 'France'})
50
db.laureates.count_documents({'bornCity': 'Warsaw'})
2
filter_doc = {'gender': 'female',
'diedCountry': 'France',
'bornCity': 'Warsaw'}
db.laureates.count_documents(filter_doc)
1
db.laureates.find_one(filter_doc)
{'_id': ObjectId('5bc56154f35b634065ba1be9'),
'born': '1867-11-07',
'bornCity': 'Warsaw',
'bornCountry': 'Russian Empire (now Poland)',
'bornCountryCode': 'PL',
'died': '1934-07-04',
'diedCity': 'Sallanches',
'diedCountry': 'France',
'diedCountryCode': 'FR',
'firstname': 'Marie',
...
$in: <list>
db.laureates.count_documents({
'diedCountry': {
'$in': ['France', 'USA']}})
258
$ne : <value>
db.laureates.count_documents({
'diedCountry': {
'$ne': 'France'}})
872
Query syntax:
{
# Match a single value exactly:
'field_name1': value1,
# Use operators:
'field_name2': {
$operator1: value1,
$operator2: value2,
... # more operators
},
... # more fields
}
$gt
, ≥ : $gte
$lt
, ≤ : $lte
db.laureates.count_documents({
'diedCountry': {
'$gt': 'Belgium',
'$lte': 'USA'}})
453
453
(Strings are compared lexicographically)
Query syntax:
{
# Match a single value exactly:
'field_name1': value1,
# Use operators:
'field_name2': {
$operator1: value1,
$operator2: value2,
... # more operators
},
... # more fields
}
Introduction to MongoDB in Python