1 Insert

db.COLLECTION.insert(doc/docs)

You can insert one document or a list of documents. When you insert a list of documents, the operation is not atomic. The returned result shows the statistics of the write operations including the write errors and the number of successfully inserted documents.

2 Find

db.COLLECTION.find({name: value, 'name1.name2.name3':value/condition})

Check all the elements in array when ‘name#’ corresponds to array. Special conditions

  • $in, $ne, $nin, $lt, $gt, $lte, $gte
  • $and, $or, $not, $nor
  • $exists, $type
  • $regex, $text, $where, $mod
  • $all, $elemMatch, $size
  • $, $slice

Difference between with/without $elemMatch is that: $elemMatch restrict that one element in array should match all the conditions, while without $elemMatch, different elements in the array can match different part of the conditions.

Match element / array can be done by query {name: value} when value is a single variable/object or an array.

Elements in array can be retrieved by index db.COLLECTION.find({'name.0': value}).

3 Select

  • get attribute
    db.COLLECTION.find(***, {name:1})
    
  • get elements in array
    db.COLLECTION.find(***, {'name1.name2':1})
    

    This projection will returns all the elments with the path ‘name1.name2’ when any one in the path represents an array.

    db.COLLECTION.find(***, {name1: {$elemMatch: {name2:value}}})
    

    $elemMatch can be used in the second argument to limit the returned elements in array. However, it CANNOT be used in nested array and only returns the FIRST element.

  • get elements in nested array.

    Aggregation framework/unwind. Aggregations are operations that process data records and return computed results. Pipeline

    You can expand the nested arrays by several $unwind operations to get a large number of documents that each one contains a single combination of elements in different levels of nested arrays. Then match the elements you need and maybe regroup them together. However, if you want to aggregate the matched elements in nested arrays into array after $unwind operation, it is very complex.

    However, you can just return the tasks by $group operation that matches, for example, the nested element attributes.

4 Update

  • update attribute:
    db.COLLECTION.update(find condition, {$set: {name: value}})
    

    $inc increase number, etc. upsert will insert element when it does not exist in collection.

  • update array:
    db.COLLECTION.update(find condition, {$push/$pull: value})
    
    db.students.update(
      { _id: 1 },
      {
      $push: {
              scores: {
                 $each: [ { attempt: 3, score: 7 }, { attempt: 4, score: 4 } ],
                 $sort: { score: 1 },
                 $slice: -3
              }
      }
    
    })
    

    The command above append 2 elements, then sort them by ascending score, then keep the last 3 elements of the ordered array.

  • update element in array:
    db.COLLECTION.update({"name1.name2":value}, {$set:{'name1.$.name2:value}})
    

    It only works for one match.

    If you want to update multiple elments, use forEach function.

    db.Projects.find().forEach(
        function(pj){
            pj.groups.forEach(
                function(gp){
                    gp.tasks.forEach(
                        function(task){
                            if (task.name.match(/update/)){
                                task.weight=5;
                            }
                        });
                });
            db.Projects.save(pj);
        }
    )
    
  • update element in nested array.

    Impossible for only one query. The issue is reported on 2010, but is still there on 2015…

Functional key words:

  • $currentDate, $inc, $max, $min, $mul, $rename, $setOnInsert, $set, $unset
  • $, $addToSet, $pop, $pullAll, $pull, $pushAll, $push
  • $each, $position, $slice, $sort

5 Remove

  • remove document
    db.COLLECTION.remove(condition)
    

    remove all documents when condition is not provided.

  • remove colleciton
    db.COLLECTION.drop()
    
  • remove database
    use DATABASE
    db.dropDatabase()
    
  • remove attribute
    db.COLLECTION.update(find, {$unset: {name: value}})
    

    value can be 1, “”, true/false.

  • remove element in array
    db.COLLECTION.update({"name1.name2":value}, {$unset:{'name1.$.name2':1}})
    

6 Commands

show dbs use DB show collection help db.help() db.COLLECTION.help()

7 Query Cursor Methods

  • count() // count of documents returned in a curcor
  • explain() // report
  • hint() // Forces MongoDB to use a specific index for a query
  • limit() // constraints size of returned results
  • skip() // skip the first number of documents
  • sort()
  • toArray()

8 MapReduce

db.COLLECTION.mapReduce(mapFunction,
                        reduceFunction,
                        {
                            query: "query performed at the beginning",
                            out: "out collection name",
                            finalize: finalizeFunction
                        })

Query -> map -> reduce -> finalize -> out.

  • The reduce function muse return object with the same type of the output of the map function.
  • The order of emited elements should not affect the output of reduce function.
  • The reduce function must be Idempotent, which means f(f(x))=f(x).