What version am I using?
Python3
use pymongo
print(f'pymongo version {pymongo.version}')
print(f'C extension installed {pymongo.has_c()}')
MongoDB server
$ mongo
> db.version()
Increment numeric value
replace.set age
> db.customers.update({first_name:"John",last_name:"Doe"},
{$set:{age:45}})
add 5 years to age
> db.customers.update({first_name:"John",last_name:"Doe"},
{$inc{age:5}}})
Sort by last name
> db.customers.find(...).sort({last_name:1}) <-- 1 is ascending order
> db.customers.find(...).sort({last_name:-1}) <-- -1 is descending order
> db.customers.find(...).sort(...).pretty()
Count documents
count all
> db.customers.find().count()
Count selected documents
> db.customers.find(...).count()
limit returned documents
> db.customers.find(...).limit(4)
Iterate thru "stuff"
> db.customers.find().forEach(
function(doc)
{print("Customer Name: "+doc.last_name)})
Create a user for this database
> db.createUser({ user:"name",
pwd:"password",
roles: ["readwrite","dbAdmin"] })
Regular expressions
lastname contains character 'e'
> db.phones.find( {lastname: {$regex: /e/}})
> db.phones.find( {lastname: {$regex: 'e'}})
> db.phones.find( {lastname: /e/})
lastname does not contains character 'e'
> db.phone.find(Lastname; {$not: /e/}})
Select returned fields
return all entries and all fields
> db.phones.find()
> db.phones.find({})
return all fields for entries with lastname = "Pete"
> db.phones.find({lastname: "Pete"})
only return field age for entries with lastname = "pete"
_id is automatically returned
> db.phones.find( {lastname: "Pete"},{age: 1})
only return field age for entries with lastname = "pete"
_id is not returned
> db.phones.find( {lastname: "Pete"},{age: 1, _id: 0})
only return field age for entries with lastname = "pete"
_id is not returned
> db.phones.find( {lastname: "Pete"},{_id: 0})
Project Fields to Return from Query
Select documents missing age field
db.phone.find(age: {$exists:false}})
db.phone.find(age: {$exists:false}}).count()
db.phone.find(age: {$exists:false}}).pretty()