MongoDB ed

mongo shell ed

basics ed

select a database
use mydatabse

list collections/databases
show collections
show databases

add/delete collection
db.createCollection("name")
db.collection.drop()

documents ed

add new document
db.collection.insertOne( {a:..., b:...} )

delete
db.collection.deleteOne(...)
db.collection.deleteMany(...)

update
db.update( {filter...}, {$set: {name: 'test', age: 14} } )

find ed

basic filtering
db.collection.find( {name: 'Some Name', age: 13} )
db.collection.find( {name: {$in: ['Name1', 'Name2', 'Name3'] } )
db.collection.find( {name: {$regex: '.*bla.*' } )

sorting
db.collection.find(...).sort( {name: 1} )

selective output
db.collection.find( {filter...}, {name: true, _id: false} )

index ed

create
db.collection.createIndex( { name: "text", author: "text", toc: "text", camera: "text" } )

searching
db.collection.find( { {$text: {$search: "something"} } )

aggregate ed

grouping
db.col.aggregate( {$group: {_id: '$artist', 'num': {$sum: 1} } } ] )

grouping after unwinding arrays
db.col.aggregate( [ {$unwind: '$author'}, {$group: {_id: '$author', 'num': {$sum: 1} } } ] )

complex
db.col.aggregate( [ {$unwind: '$author'}, {$sort: {author: -1}}, {$group: {_id: '$author', 'num': {$sum: 1} } } ] )
db.col.aggregate( [ {$match: {artist: 'Stratovarius'} }, {$unwind: '$album'}, {$sort: {year: -1} }, {$group: {_id: '$album', 'num': {$sum: 1} } }, {$limit: 200} ] )
db.col.aggregate( [ {$unwind: "$artist"}, {$group: {_id: "$artist", count: {$sum: 1}, total_size: {$sum: "$size"} } } ] )

pymongo ed

init
from pymongo import MongoClient
client = MongoClient()
db = client.some_database

find
r = db.col.find( { ... } )
for doc in r:
    ...
doc = db.col.find_one( { ... } )
if doc:
    ...

some actions
db.col.count_documents( { ... } )
db.col.aggregate( [ ... ] )

insert
r = db.col.insert_one( { ... } )
r.inserted_id

update
r = db.col.replace_one( { ... } )
if r.matched_count < ...

delete
r = db.col.delete_one( { ... } )
if r.deleted_count  < ...

Categories: Computer