MONGODB FOR DEVELOPERS – WEEK2

Leave a comment

October 19, 2016 by oneOokay

好洗翻我的新键盘呀咔哒咔哒咔哒

OCT 18.

Creating Documents:

  • insertOne()
    • db.foo.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 db.foo.insertMany({}, {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:

  • db.foo.find().count(): records matching all criteria in find
  • db.foo.find({“A”: aaa, “B”: “bbb”})
  • db.foo.find({“A.C”:ccc})
  • db.foo.find({“A”:[AAA, BBB]}) : find a document that the array field A matches exactly [AAA,BBB]
  • db.foo.find({“A”:AAA}): find a document that the array field A contains element AAA.
  • db.foo.find({“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.
    • db.foo.find({“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
    • db.foo.find({runtime: {$gte: 90, $lte: 120}}): find records that runtime is >= 90 and <=120
  • $ne: not equal to
  • $in must be used in an array: db.foo.find({rated: { $in: [“G”, “PG”]}})
  • $nin: not in

Element Operators:

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

Logical Operators:

  • $or: db.foo.find({$or:[{“A.B”: {$gt: 90}},  {“C.D”: {$gt: 90}}]}): find records that A.B > 90 or C.D > 90
  • $and: db.foo.find({$and: [{“A.B”: {$gt: 90}}, {“C.D”:{$gt:90}}]}): this is will return the same result as : db.foo.find({“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: db.foo.find({“A.B”: {$regex: /^Won.*/}}): return records that A.B field values matches the regex pattern

Array Operators:

  • $all: db.foo.find({A: {$all: [“B”,”C”,”D”]}}): returns records that A array contains all the elements “B”,”C”,”D”
  • $size: db.foo.find({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():
    db.foo.updateOne({}, {$set:{}}); update the first one record it finds.

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

PyMONGO:

def find():
   query = {'type' : 'exam'}
   try:
      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):
         break

find_one():

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

projection:

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: db.foo.find().sort({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.

upsert:

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

delete:

doc.deleted

MongoDb: find_and_modify():

  • find_one_and_delete:
  • find_one_and_replace
  • find_one_and_update

db.grades.find({$and:[{“type”:”exam”},{“score”:{$gte:65}}]}).sort({“score”:1})

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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: