









Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
A comprehensive overview of various mongodb query and update operations. It covers topics such as the $type operator, gridfs, transactions, indexing, querying, sorting, pagination, and different update methods like replacement, modification, and array operations. The document also discusses the use of operators like $gt, $lt, $in, $nin, $or, $and, $exists, $elemmatch, $where, and regular expressions for advanced querying. Additionally, it covers topics related to aggregation, counting, and updating documents. This document would be highly useful for students and professionals working with mongodb to gain a deeper understanding of the database's querying and update capabilities.
Typology: Exams
1 / 15
This page cannot be seen from the preview
Don't miss anything!










What is MongoDB? - Answers -A non-relational, schemaless store of JSON documents Schemaless - Answers -Two documents do not have to have the same schema Which features did MongoDB omit to retain scalability (2)? - Answers -(1) Joins, (2) Transactions across multiple collections What are the two data structure that live within JSON? - Answers -(1) Arrays - lists of things, (2) Dictionaries - associative maps dynamic typing - Answers -A programming language is said to be dynamically typed, or just 'dynamic', when the majority of its type checking is performed at run-time as opposed to at compile-time. In dynamic typing, types are associated with values not variables. static typing - Answers -A programming language is said to use static typing when type checking is performed during compile-time as opposed to run-time. In static typing, types are associated with variables not values. What's the primary difference between Python dicts and JSON dictionaries? - Answers - JSON dictionaries preserve the order of the key-value pairs whereas Python dicts are orderless. Python exception handling - Answers -import sys. try: "code" , except: print "exception ", sys.exc_info()[0] CRUD - Answers -"Create Read Update Delete" --> "Insert Find Update Remove". Things that can be performed on records. Does MongoDB have its own query language? - Answers -No, Mongo's CRUD operations exist as methods/functions in programming language APIs, not as separate language What is the interactive language for the MongoDB shell? - Answers -JavaScript - can type it right in the shell! BSON - Answers -Binary representation of JSON. Supports basic data types that Mongo contains. How does MongoDB's < / > query operators work for strings? - Answers -Retrieves based on Ascii character order. Case sensitive. Ex: db.uses.find({name:{$gte :"F", $lte:"Q"}}) <> db.uses.find({name:{$gte :"f",$lte:"Q"}})
What does $type do while using the "find" method - Answers -Returns values from the specified field that match the character type. $type values are numeric and correspond to the BSON type as specified in the BSON documentation. What's the single most important factor in designing your application schema with MongoDB? - Answers -Matching the data access patterns of your application Rich documents - Answers -More than just tabular data. Includes arrays, key-values, etc. Allows for "pre-joins" or embedded data Does MongoDB have constraints? (ex: FK constraints) - Answers -Nope. Less of an issue b/c of embbedding Atomic operations - Answers -An operation during which a processor can simultaneously read a location and write it in the same bus operation. This prevents any other processor or I/O device from writing or reading memory until the operation is complete. What are the goals of normalization in relational databases? (3) - Answers -(1) free the database of modification anomalies, (2) minimize redesign when extending, and (3) avoid bias toward any particular access pattern Access pattern - Answers -An access pattern is a specification of an access mode for every attribute of a relation schema, i.e., it is an indication of which attributes are used as input and which ones are used as output. What can you do to make your MongoDB 'schema' more effective. - Answers -Embed and pre-join anywhere you can. ACID - Answers -"Atomicity, Consistency, Isolation, Durability". A set of properties that guarantee that database transactions are processed reliably. database transaction - Answers -A transaction comprises of a unit of work performed within a DBMS against a database and treated in a coherent and reliable way independent of other transactions. atomicity (ACID) - Answers -When a series of database operations either all occur or nothing occurs. Prevents updates to the database occurring only partially. consistency (ACID) - Answers -Guarantee that database constraints are not violated, particularly once a transaction commits. isolation (ACID) - Answers -How transaction integrity is visible to other users and systems.
What's the primary difference between Python dicts and JSON dictionaries? - Answers - JSON dictionaries preserve the order of the key-value pairs whereas Python dicts are orderless. Python exception handling - Answers -import sys. try: "code" , except: print "exception ", sys.exc_info()[0] CRUD - Answers -"Create Read Update Delete" --> "Insert Find Update Remove". Things that can be performed on records. Does MongoDB have its own query language? - Answers -No, Mongo's CRUD operations exist as methods/functions in programming language APIs, not as separate language What is the interactive language for the MongoDB shell? - Answers -JavaScript - can type it right in the shell! BSON - Answers -Binary representation of JSON. Supports basic data types that Mongo contains. How does MongoDB's < / > query operators work for strings? - Answers -Retrieves based on Ascii character order. Case sensitive. Ex: db.uses.find({name:{$gte :"F", $lte:"Q"}}) <> db.uses.find({name:{$gte :"f",$lte:"Q"}}) What does $type do while using the "find" method - Answers -Returns values from the specified field that match the character type. $type values are numeric and correspond to the BSON type as specified in the BSON documentation. What's the single most important factor in designing your application schema with MongoDB? - Answers -Matching the data access patterns of your application Rich documents - Answers -More than just tabular data. Includes arrays, key-values, etc. Allows for "pre-joins" or embedded data Does MongoDB have constraints? (ex: FK constraints) - Answers -Nope. Less of an issue b/c of embbedding Atomic operations - Answers -An operation during which a processor can simultaneously read a location and write it in the same bus operation. This prevents any other processor or I/O device from writing or reading memory until the operation is complete. What are the goals of normalization in relational databases? (3) - Answers -(1) free the database of modification anomalies, (2) minimize redesign when extending, and (3) avoid bias toward any particular access pattern
Access pattern - Answers -An access pattern is a specification of an access mode for every attribute of a relation schema, i.e., it is an indication of which attributes are used as input and which ones are used as output. What can you do to make your MongoDB 'schema' more effective. - Answers -Embed and pre-join anywhere you can. ACID - Answers -"Atomicity, Consistency, Isolation, Durability". A set of properties that guarantee that database transactions are processed reliably. database transaction - Answers -A transaction comprises of a unit of work performed within a DBMS against a database and treated in a coherent and reliable way independent of other transactions. atomicity (ACID) - Answers -When a series of database operations either all occur or nothing occurs. Prevents updates to the database occurring only partially. consistency (ACID) - Answers -Guarantee that database constraints are not violated, particularly once a transaction commits. isolation (ACID) - Answers -How transaction integrity is visible to other users and systems. durability (ACID) - Answers -Guarantee that transactions that have committed will survive permanently. What are two reasons you might want to keep two documents that are related to each other one-to-one in separate collections? - Answers -1) to reduce the working set size of your applications, (2) because the combined size of the documents would be larger than 16MB. When is it recommended to represent a one to many relationship in multiple collections?
help - Answers -Command to list commands and descriptions of those commands in the context of the database. db.help([commandName]); - Answers -Command to get help docs on a specific command at the db level. db.
embedded document - Answers -A document contained by a parent document. The embedded document is a value of a key in the parent document. batch insert - Answers -... Object.bsonsize({document}); - Answers -Returns the size of a document after it is converted to BSON from the JSON-like original. Update Modifiers - Answers -Special keys passed in an update call to specify complex update operations, such as alter, adding, or removing keys, and even manipulating arrays and embedded documents. $inc - Answers -Update modifier used to increment a value. ex: {"$inc":{"counter":2}} $set - Answers -Update modifier that set the value of a key and if the key does not exist, it will create the key. ex: db.
key.index - Answers -Syntax used for selectors to be specific to a certain element position within an array. ex: db.
how to avoid doing "select *" equivalent in mongo...how to return desired fields only - Answers -db.users.find({ email: '[email protected]' } , { title: 1, url: true }) ... this query will return "_id", "title", and "url" fields how to exclude field from search results - Answers -same as above, but do {title: 0 (or false)} ...will return all fields except title caveat of include and exclude - Answers -can't run include and exclude in same query, with exception of can exclude _id field { title:1, url: 1, _id: 0} query within sub-objects - Answers -db.users.findOne({ 'name.first' : 'John' }, { 'name.last' : 1}) ...this will return specific document, including "id" and name.last fields only. select john from user collection and query which links he's made from the links collection using his userid - Answers -var john = db.users.findOne({'name.first':'John'}); db.links.find({ userId: john._id }, { title: 1, _id: 0}); when to use operators in MongoDB - Answers -when we don't know exact value of field basic query 'greater than' syntax - Answers -db.links.find({ favourites: { $gt: 50 } }); find all documents where favourites is gt 50 and less than 150 - Answers - db.links.find({ favourites: {$gt:50, $lt:150} }, {title:1, favourites:1, _id:0}); find all users where name.first is john or jane - Answers -db.links.find({ 'name.first': { $in: ['John', 'Jane'] } }, { 'name.first':1, _id:0}); negative form of $in - Answers -$nin (not in) if one of the values in tags is 'marketplace' or 'code', return document - Answers - db.links.find({ tags: { $in: ['marketplace', 'code'] } }); $all vs $in - Answers -$all returns document if all in query array match ...plus $all does expect itself to be working on an array field, whereas $in could work on sub-object like name.first ($in can work within { name: {first: 'John'} } find all tags whose value is not equal to code - Answers -db.links.find({ tags: { $ne: 'code' }}); ...y not $nin $or operator...find all documents where first name is John OR last name is Wilson - Answers -db.users.find({ $or: [ {'name.first': "John" }, {'name.last': "Wilson"} ] }, {name: 1});
search using regex and include another operator - Answers -db.links.find({ title: { $regex: /tuts+$/, $ne: "Mobiletuts+" } } ); find all documents and count how many there are - Answers -db.users.find().count() OR db.users.count() find all documents and display their titles - Answers -db.links.find({ }, { title: 1, _id:0}); ...remember that db.links.find() returns all documents in links sort alphabetically - Answers -db.links.find({}, { title: 1, _id: 0}).sort({ title: 1}); (can also sort by -1) return top favourites score with .limit() - Answers -db.links.find({}, { title:1, favourites:1, _id: 0}).sort({ favourites: -1}).limit(1); "paging" with .skip() - Answers -db.links.find({}, {title:1, _id:0}).skip(03).limit(3); db.links.find({}, {title:1, _id:0}).skip(13).limit(3); db.links.find({}, {title:1, _id:0}).skip(2*3).limit(3); two ways to update - Answers -update by replacement & update by modification update by replacement - Answers -db.users.update({ 'name.first' : 'John' }, { job: 'developer'}); ... completely replaced all fields with {job: 'developer'} how update works - Answers -.update({query}, {replacement object}, upsert boolean) if upsert field set to true - Answers -if query object does not exist, will insert replacement object update by modification...$inc - Answers -db.links.update({title: "Nettuts+"}, { $inc: { favourites: 5} }); ... can also increment by - query vs modification operator orders - Answers -with query operators, key is outside and operator is inside...with modification operators, operator is outside update by modifying text - Answers -db.users.update(q, { $set: { job: 'Web Developer' } }); update by inserting text - Answers -db.users.update(q, { $set: { email: '[email protected]'} }); update by removing text - Answers -db.users.update(q, { $unset: { job: 'Web Developer" } });
update's fourth parameter - Answers -multi...set to true if you want to update documents other than the first one returned...however only works with modification, so upsert (3rd parameter) must be set to false .save() (save method) - Answers -var bob = db.users.findOne({ 'name.first' : 'Bob' }); bob.job = "Server Admin" db.users.save(bob) .findAndModify() - Answers -db.users.findAndModify({ query: { name: "Kate Wills" }, update: { $set: { age: 20} }, new: true }); default for new is false...if you want .findAndModify to return new (instead of prior) object, set to true. $push operator - Answers -add item into an array [] $push example - Answers -db.links.update(n, { $push { tags: 'blog' } }); $pushAll - Answers -db.links.update(n, { $pushAll { tags: ['one', 'two'] } }); like $push except only adds unique items to set - Answers -$addToSet instead of $push $addToSet when we want to add multiple items without duplicating any already existing