Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@slitayem
Last active March 19, 2018 06:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save slitayem/60a24927be3e7ca48dd2a986fdddcb2e to your computer and use it in GitHub Desktop.
Save slitayem/60a24927be3e7ca48dd2a986fdddcb2e to your computer and use it in GitHub Desktop.
Mongodb 3.x cheat sheet

Note: Tested on mongodb 3.4.1

Creating Collections, Documents, Indexes

See: MongoDB CRUD Operations

Command Description
db.createCollection("movies") Explicitly create a collection
db.movies.insertOne({movie_id: "abc123", reviews: 93, year: "2001", "imdb": "t0081234"}) Create a documents in the collection and creates the collection of the collection did not already exist. The primary key _id is automatically added if_idfield is not specified.
db.users.ensureIndex( { movie_id: 1 } ) Create index on movies_id in movies collection.
db.movies.insertMany([{...}, {...}], "ordered": False) Insert a list of documents. 'ordered' field is used to continue or not the insertion in case of occurring exception while inserting the documents.

Reading documents

Query Description
db.movies.find( {rated: "PG-13", "year": 2006}).pretty() find all documents matching all the criteria are retrieved. Selectors in the query document for find are implicitly anded together.
db.movies.find({rated: "PG-13", "year": 2006}).count() Count all the documents matching the criteria.
db.movies.find({"actors.name": "Tom Hanks"}) Using dot notation to match the document nested within the field actors
db.movies.find({writers: ["Ethan Coen", "Joel Coen"]}) Identify documents by an exact match to an array of one or more values. For this type of queries the order matters.
db.movies.find({writers: "Ethan Coen"}) Find all documents where any element in the array field matches the specified field value
db.movies.find({"actors.0": "Tom Hanks"}) Match a specific element occurring in a specific position in an array. Here the query retrieves only movies where Tom Hanks was the start(first position the array).

Cursors and projection

The find method returns a cursor. To access documents we need to iterate through the cursor. In the mongo shell if we don't assign the returned value to variable using the var keyword, the cursor is automatically iterated up to 20 times to print a initial set of the search results.

In general, mongodb server returns the results in batches. Batch size will not exceed the maximum BSON document size. And for most queries the first batch returns 101 documents or just enough documents to exceed one megabyte. Subsequent documents will be four megabytes. It is possible to override the default batch size.

var c = db.movies.find();
// get number of objects in the batch
c.objsLeftInBatch();
var doc = function() { return c.hasNext() ? c.next(0: null;}
// iterate through the batch by calling the function doc
doc()
doc()
// See how many documents are left in the batch
c.objsLeftInBatch();

Projection

A handy way of reducing the size of the data returned for any one query. Projections reduce network overhead and processing requirements by limiting the fields that are returned in results documents.

  • db.movies.find({year: 2017}, {title: 1, _id: 0}) retrieve only title field and explicitely excluding the _id field
  • db.movies.find({year: 2017}, {writers: 0, actors: 0}) retrieve all field except writers and actors fields.

Comparison Operators

For more details see Comparison Query Operators

  • db.movies.find({ runtime: { $gte: 95 , $lt:120}}, {title: 1, runtime: 1}) Get movies with runtime in [90, 120]

Element Operators

  • $exists Matches documents that have the specified field. e.g: db.movies.find({"tomato.review": {$exists: false}})
  • $type Selects documents if a field is of the specified type. e.g: db.movies.find({"_id": {$type: "string"}})

Logical Operators

$or, $and, $not, $nor

e.g:

db.movies.find(
  {"$or": [{actor: "Tom Hanks",
          rate: {"$gt": 6}}
        ]
  })
db.movies.find(
  {"$and": [{metacritic: {"$exists": true},
          metacritic: {"$ne": null}
        ]
  })

Regex Operators

  • $regex: e.g: db.movies.find({"award.text": {"$regex": /^Won\s.*/} })

Array Operators

  • $all: Matches arrays that contain all elements specified in the query.
db.movies.find({ genres: { $all: ["Comedy", "Crime", "Drama"] } }).pretty()
  • $size Matches arrays that have the specified size
db.movies.find({ countries: { $size: 1 } }).pretty()

-$elemMatch: Select documents if element in the array field matches all the specified $elemMatch conditions.

// field example
boxOffice: [ { "country": "USA", "revenue": 41.3 },
             { "country": "Australia", "revenue": 2.9 },
             { "country": "UK", "revenue": 10.1 },
             { "country": "Germany", "revenue": 4.3 },
             { "country": "France", "revenue": 3.5 } ]
db.movies.find({ boxOffice: {$elemMatch: { country: "UK", revenue: { $gt: 15 } } } })

Updating documents

  • updateOne: Update the first document matching the selector

Examples:

Add poster field to the document

db.movies.updateOne({title: "The Martian"},
  { $set: {poster: "http://ia.media-imdb.com/images/M/MV5BMTc2MTQ3MDA1Nl5BMl5BanBnXkFtZTgwODA3OTI4NjE@._V1_SX300.jpg"} })

Add a list of reviews on the beginning of the list and keep only the 5 most recent reviews.

db.movies.updateOne({title: "The Martian"},
{$push: { reviews:
          { $each: [
              { rating: 0.5,
                date: ISODate("2016-01-12T07:00:00Z"),
                reviewer: "Yabo A.",
                text: "..."},
              { rating: 5,
                date: ISODate("2016-01-12T09:00:00Z"),
                reviewer: "Kristina Z.",
                text: "..."} ],
            $position: 0,
            $slice: 5 } } } )
  • updateMany Apply all the modifications to all documents that match the filter

Examples: Unset all the fields rated that are set to null

db.movies.updateMany( { rated: null },
  { $unset: { rated: "" } } )

For more details see Update operators reference doc

Upserts

If the filter does not match any document in the collection, a new document will be created. example:

db.movies.updateOne(
    {"imdb.id": 12345},
    {$set: {...}},
    {upsert: true});

The Aggregation Pipeline

  • $project: Re-shape the document. This stage is 1:1 in term if its handling of the documents.
  • $match: n:1 filtering
  • $group: Group together the documents and perform the aggregation functions. It is an n:1 stage
  • $sort Sort the documents in a particular order.
  • $skip: Skip some documents. It is an n:1 transformation.
  • $limit: Limit the number of documents that come out of the stage. It is an n:1 transformation.
  • $unwind: Normalize the data by flattening the documents. It is a 1:n stage. If in any of the documents we have an array of n elements, then we will get n documents out.
  • $out: Redirect the output of the aggregation to a collection. It is a 1:1 stage.
  • $redact
  • $geonear
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment