MongoDB CheatSheet
Collection of Mongo Utilities and Queries. Types of collection queries: -COLLSCAN for a collection scan -IXSCAN for scanning index keys -FETCH for retrieving documents -SHARD_MERGE for merging results from shards
Update one field with the value of another (name will be the code)
db.getCollection("vehicles").updateMany( {}, [{ $set: { name: "$code" } }] )
#Export mongoexport --uri mongodb+srv://xxx:aaa@xpto.abc.mongodb.net/cars --collection slots --type json --out slots.json
Sum all array elements from properties
db.cars.aggregate([{$unwind:"$models"}, {$group: {_id: "models", models: {$sum: 1}}}])
Delete Many
db.getCollection("races").deleteMany( { "day" : { $gte: ISODate("2021-10-01T10:00:00.000+0000") } } );
Match null
previousAvailableUnits" : { $type: 10 } } https://docs.mongodb.com/manual/reference/bson-types/
Sparse Indexes
db.getCollection("cars").getIndexes(); db.getCollection("cars").dropIndex("specs.engines"); db.getCollection("cars").createIndex( {"specs.engines": 1}, {unique:true, sparse:true} )
Index usage
db.slots.aggregate( [ { $indexStats: { } } ] )
create db
use DATABASE_NAME
misc commands
db show dbs db.movie.insert({"name":"tutorials point"}) show collections
Dump and Restore
docker run -v "$(pwd)":/var -p 27017:27017 -it --name mongo /bin/sh mongodump --uri mongodb+srv://:@my-cluster.mongodb.net/radeon mongorestore --uri mongodb+srv://:@my-cluster1.mongodb.net
Query context on subdocuments (ANDs, ORs)
{"races": { $elemMatch: {"gearBoxType": ObjectId("5f2517c427365836a2802bbd") }} }
Find duplicate fields between documents
db.slots.aggregate( {"$group" : { "_id": "$appointments.bookingReference", "count": { "$sum": 1 } } }, {"$match": {"_id" :{ "$ne" : null } , "count" : {"$gt": 1} } }, {"$project": {"appointments.bookingReference" : "$_id", "_id" : 0} } )
Load Data from S3 into MongoDB
aws s3 cp s3://<fileURI> - | mongoimport --db <dbname>--collection <collectionName>
Add a field to all docs
db.users.update( {}, { $set: {"groups": []} }, false, true )
HealthCheck
db['impressions-150518'].stats();
Update multiple docs
db.workflows.updateMany( { completed: null }, { $set: { completed: false } } ) db.workflows.updateMany({}, { $set: { durationDays: NumberInt(1) } } )
Find all the records containing the character "-"
{ "amount": { $not: /.-./i } }
Search by ObjectId
{ "transactions": ObjectId("5a608971ac610c06d296cd37") }
Array length
{ $where: "this.telemetrylogs.length < 5" } { $and: [ { $where: "this.telemetrylogs.length < 5" }, { $where: "this.telemetrylogs.length > 0" } ] } { $and: [ {subscriptions: {$exists: true}}, {subscriptions: {$ne: null}}, { $where: "this.subscriptions.length > 1" } ] }
And Aggregation
{ $and: [ {status: {$ne:"success"}}, {status: {$exists:true}} ] }
Regex for last characters
{ "accountNr": { $regex: /500$/ } }
Search by name (implicit regex)
{ "name": /adf/i }
Regex for unwanted words
{$and: [{ "createdAt": { $gte: ISODate("2018-01-01T10:00:36.825+0000") } } , {"email": /^((?!code|recipes|test).)*$/gm} ] }
Negative Regex for unwanted words
{ "invoiceNumber": { $regex: /^((?!XPTO).)/ } }
Query by Date
{ "executionDate": { $gte: ISODate("2016-08-06T10:21:36.825+0000") } }
Query within 2 dates
{ $and: [ { "executionDate": { $gte: ISODate("2017-11-17T00:00:00.00+0000") } }, { "executionDate": { $lt: ISODate("2017-11-17T23:59:00.00+0000") } } ] }
Query if Field exists and is not null
{ $and: [ {telemetry: {$exists: true}}, {telemetry: {$ne: null}} ] }
Query to check if default values were modified
{ $and: [{ "props.balance": { $ne: 0 } }, { "props.balance": { $exists: true }}] }
Negative Amount
{ "amount": { $lt: "0" } }
Array Length
{ $and: [ { "additionalServices": {$exists: true } }, { $where: "this.additionalServices.length > 0" } ] }
Create Index
db['impressions-310518'].createIndex({ "pathMeta.CampID": 1 }) db.getCollection("pushsubscriptions").createIndex({ "deleted": 1 }, { background: true })
Get Indexes
db['impressions-310518'].getIndexes()
Create Unique Indexes
db.pushsubscriptions.createIndex({endpoint: 1}, {unique: true})
Find whitespaces in strings
{ "originalId" : /\s+/gi }
Add ids from one collection to the other one
//db.users.update( // {}, // { $set: {"groups": []} }, // false, // true //)
// Quarter of Users db.patches.count(); db.users.count(); patchIds = db.patches.find().skip(65).map( function(doc) { return doc._id; } ); userIds = db.users.find().skip(45).map( function(doc) { return doc._id; } ); db.users.updateMany({_id: {$in: userIds}}, { $set: {"patches": patchIds} });
Created on 11/13/2017