Leave a comment

October 19, 2016 by oneOokay


OCT 18.

Creating Documents:

  • insertOne()
    •{“_id”:aaaa}): aaaa will be its _id. Without “_id”, mongodb will always create a default one.
  • insertMany(): bulk insertion. In order by default. when it encounters an error, it will stop.
    • Add this{}, {ordered:false}): it will skip error records and continue inserting other record
  • Update commands (“Upserts”)

The _id Field:

  • 12 byte hex string:
    • date/mac address/pid(process id)/counter
    •  —-/—/–/—

Reading Documents:

  • records matching all criteria in find
  •{“A”: aaa, “B”: “bbb”})
  •{“A”:[AAA, BBB]}) : find a document that the array field A matches exactly [AAA,BBB]
  •{“A”:AAA}): find a document that the array field A contains element AAA.
  •{“A.0”:AAA}): find a document that the array field A’s first element is AAA.
  • Cursors:
    • var c = db.fool.find();
    • c.objsLeftInBatch();
  • Projections: are supplied as the second elements for the find command.
    •{“A”:AAA}, {“title”:1, “_id”:0}): will return “title” attribute values; “_id” will always be returned unless set to 0. 1: include; 0: exclude.

Comparison Operators:

  • $gt: greater than; $gte: greater than and equal t0; $lt; $lte
    •{runtime: {$gte: 90, $lte: 120}}): find records that runtime is >= 90 and <=120
  • $ne: not equal to
  • $in must be used in an array:{rated: { $in: [“G”, “PG”]}})
  • $nin: not in

Element Operators:

  • $exists:{“A.B”: {$exists: true}}): returns records that have A.B field.
  • $type:{“_id”:{$type: “string” }}: returns records that their _id type is string.

Logical Operators:

  • $or:{$or:[{“A.B”: {$gt: 90}},  {“C.D”: {$gt: 90}}]}): find records that A.B > 90 or C.D > 90
  • $and:{$and: [{“A.B”: {$gt: 90}}, {“C.D”:{$gt:90}}]}): this is will return the same result as :{“A.B”:{$gt: 90}}, {“C.D”:{$gt:90}}}).
    • we still need $and is because when we specify multiple criteria on one key for more than one time.

Regex Operator:

  • $regex:{“A.B”: {$regex: /^Won.*/}}): return records that A.B field values matches the regex pattern

Array Operators:

  • $all:{A: {$all: [“B”,”C”,”D”]}}): returns records that A array contains all the elements “B”,”C”,”D”
  • $size:{A:{$size:1}}): returns records that A array size is 1.
  • $eleMatch: all the criteria be satisfied within a single array field

Updating Documents:

  • updateOne():{}, {$set:{}}); update the first one record it finds.

    • $unset:
    • $min
    • $max
    • $inc:
    • $push:
    • $each
    • $slice
    • $position
    •{},{$set: XXX},{upsert: true}): third element: upsert.
  • UpdateMany():
  • replaceOne()


def find():
   query = {'type' : 'exam'}
      cursor = scores.find(query)
   except Exception as e:
   print "Unexpected error: ", type(e), e
   sanity = 0
   for doc in cursor:
      print doc
      sanity += 1
      if (sanity > 10):


query = {'student_id' : 10}
doc = scores.find_one(query)


query = {'type' : 'exam'}
projection = {'student_id':1}
cursor = scores.find(query, projection)

$gt $lt in pymongo:

  • query = {‘type’:’quize’, ‘score’:{‘$gt’:20,’$lt’:80}}

Sort, Skip and Limit

  • cursor = scores.find(query).sort(‘student_id’, pymongo.ASCENDING).skip(4).limit(1)
  • Database doesn’t run the query until the cursor starts iteration. Database always do Sort FIRST, then Skip, last Limit.
  • mongo shell:{A:1, B:-1}).limit(2): sort foo by A ascending B descending and return 2 results
  • pymongo: cursor = scores.find(query).sort([(‘student_id’, pymongo.ASCENDING), (‘score’, pymongo.DESCENDING)])
  • JSON retains the order of key value pairs. Dictionary in python are not ordered.

pymongo and server commands comparison:

  • Inserting: pymongo: insert_one; server: insert. pymongo: insert_many; server: bulk.
  • Updating: pymongo: update_one, update_many, replace_one; server: update.
  • Deleting: pymongo: delete_one, delete_many; server: remove.

insert_many: insert_many([],ordered=True): if ordered = True, then MongoDB has to maintain the order or once it errorred out, it will stop right at where it throws exception. If ordered = False, it will skip all the error records and keep inserting all other correct records.

update_one(filter, update): update operations including $set and so on.

scores.update_one({'student_id':1, 'type':'homework'},
                      '$set': {'examiner':'Jones'})

update_many(filter, update):

replace_one: if you want to do an increment a counter, use update_one/find_and_modify  instead of replace_one because during the process of replace_one, the original record might have be updated.


  • things.replace_one({‘thing’:’pear’}, {‘color’:’green’}, upsert=True): This will create a document {‘color’:’green’} ONLY, not {‘thing’:’pear’, ‘color’:’green’}.



MongoDb: find_and_modify():

  • find_one_and_delete:
  • find_one_and_replace
  • find_one_and_update


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: