0% found this document useful (0 votes)
69 views

MongoDB CheatSheet

The document provides a cheat sheet on MongoDB with information on basics, CRUD operations, aggregation, transactions, replication and sharding. It covers starting and stopping MongoDB, databases and collections, main data types, dates, references and queries. CRUD operations include insert, find, update and delete. Aggregation includes pipeline operators and result processing methods.

Uploaded by

Google User
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
69 views

MongoDB CheatSheet

The document provides a cheat sheet on MongoDB with information on basics, CRUD operations, aggregation, transactions, replication and sharding. It covers starting and stopping MongoDB, databases and collections, main data types, dates, references and queries. CRUD operations include insert, find, update and delete. Aggregation includes pipeline operators and result processing methods.

Uploaded by

Google User
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

MongoDB Cheat Sheet > CRUD > Aggregation pipeline

>> Create: Insert


David Brau | 2023 database> db.collection.insertOne({document})
database> db.collection.aggregate([ {$pipelineOperator1:options1},
{$pipelineOperator2:options2}])
database> db.collection.insertMany([documents])
> Basics >> Pipeline operators
> Input - Output
>> Start / Stop MongoDB
>> Read: Find
database> db.collection.findOne()
$lookup:{ from:”database2”, localField: “localfield”
foreignField:”foreignField”, as:”arrayDest”}}
$ sudo service mongod start
Mongoimport $ sudo service mongod stop database> db.collection.find({field:value},{projection}).resultProcessingMeth() |Docs from db2 with foreign=local added to arrayDest
database> db.collection.find({field1:value1, field2:value2}, | Plain Search $unwind:$preArrayField
>> Mongosh {_id: false, field1: true}) | Projection $match:{field:value} | Like find()
.\mongoimport
$ mongosh --port 27017-d sh .option1().option2() | Options $project:{postField2:{$projectOperator:value}}
database> show databases ⇔ database> show dbs database> db.collection.find({logicQuerySelector:[{field1:value1}, $group:{_id:idField, | _id:null → All in the same group
database> show collections ⇔ database> show tables {field2:value2}]}) postField2:{$accumulator:value}}
database> use database database> db.collection.find({field1:{querySelector1:value1}, postField3:{$accumulator:$preField3}}
database> db.dropDatabase() | Remove database {field2:{querySelector2:value2}}) $sort:{pre&postField: -1} $sort:{pre&postField: 1}
database> db.collection.drop() | Remove collection from database $limit:numLimit
>>> Comparison query selectors: >>> Logic query selectors: |Match and sort don’t use $Field
>> Main data types $eq:value $and:[] $or:[]
>>> Object >>> Decimal $ne:value $not:[] $nor:[] >> Accumulators:
>>> Array >>> ObjectId $gt:value
$sum: $first $avg: $max:
>>> String >>> Date $gte:value >>> Array query selectors:
$multiply: $last $count $min:
>>> Boolean >>> TimeStamp $lt:value $all:[]
>>> Integer >>> Binary Data $lte:value $size:integer
$in:[value1, value2] $elemMatch:{queries} >> Project Operators:
>>> Double >>> Null
$nin:[value1, value2] $substr $subtract: $toUpper $if
>> Date >>> Element query selectors:
{myDate:new Date(“YYYY-MM-DD”)} >>> Evaluation query selectors:
$mod:value | Module
$exists:boolean
$type:bsontype
> Transactions
{myDate:ISODate(“YYYY-MM-DDThh:mm:ssZ”)} database> session = db.getMongo().startSession()
$text:options
database> session.startTransaction()
$where:function(){...}
>> Reference and Dot notation database> db.collection.query1() database> db.collection.query2() ...
$regex:/regulareExpression/
>>> Fields and selectors may be used with or without quotation marks, database> session.commitTransaction()
whereas strings must always be enclosed in quotation marks.
>>> Dot notation for field reference:
>>> Result processing methods:
.countDocuments() ⇔ .count() .toArray() > Replication and Sharding
Field.subfield.subsubfield…
.sort(0) | Descendent .sort(1) | Ascendent $ mongod --configsvr --replSet configName --port 27021 --dbpath path/to/folder
Field[position].subfield.subsubfield[position]…
.limit(n) | n first results .skip(n) | skip n first results $ mongod --shardsvr --replSet shardName --port 27022 --dbpath path/to/folder
.forEach() -- oplogSize 50 | Max oplog size in MB
> Input - Output .map(func(){…}) |Applies func to matches and returns [results] (27022) database> rs.initiate({_id : shardName, members: [
{ _id:0, host:IP:27022, priority:100},
>> Mongoimport
>> Update: Update { _id:1, host:IP:27023, priority:50}]})
$ mongoimport -d database -c collection -f path/to/file.json
database> db.collection.updateOne({search}, {updateOperator: $ mongos --configdb configServerName/IP:27021 --port 27026
$ mongoimport --db database --collection collection --file path/to/file.json
{field1:change1, field2:change2}}) (27026) database> sh.addShard("shardServersName/IP:27022,IP:27023")
database> db.collection.updateMany({search}, {updateOperator:{field:change}}) (27026) database> sh.status()
>> Mongoexport (27026) database> sh.enableSharding("database")
database> db.collection.replaceOne({search}, {changes})
$ mongoexport --uri mongodb://localhost:27017/database (27026 )database> sh.shardCollection("database.collection",
--collection collection --out path/to/file.json {"partitionKey":"hashed"})
>>> Update operators:
$set:{field:newValue} $unset:{field:1} $ mongod --shardsvr --replSet shardName --port 27027 --dbpath path/to/folder
--oplogSize 50 | New server added after
> Index $inc:{field:incrementNumber} $mul:{field:multiplyNumber}
$rename:{field1:newName1, field2: newName2}
Index
>> Get
database> db.collection.getIndexes()
$currentDate:{field1:true, field2:true}
$push:{array:{json}}
> Regular expressions
/myword/ | Like myword
$pull:{array:{json}} $pullAll:{array:[val1, val2]}
/myword/i | Like myword no case sensitive
>> Create / Delete /myword.*/ | Like myword + whatever
database> db.collection.createIndex({field1:1, field2:-1}) >> Delete: Delete /^myword$/ | Starts and ends with myword
database> db.collection.createIndex({field1:1},{unique: true}) database> db.collection.deleteOne({field1:value1, field2:value2}) /[A][B|C][D]/ | ABD or ACD
database> db.collection.dropIndex({field1:1}) database> db.collection.deleteMany() /[A-Z|a-z|0-9]/ | A letter or a number

You might also like