credit: https://www.youtube.com/watch?v=ogtqMXMpTA4 In this post, we’re going to see a few example of operation in CRUD MongoDB Restoring using mongorestore After making sure that and are running, go to the dump’s parent directory in a new terminal. And use the command . Where is the folder name in which the dump is present. mongod mongo mongorestore dump dump database Creating Documents There’re two principal commands for creating documents in MongoDB: There’re other ways as well such as commands. We call these operations, upserts. Upserts occurs when there’re no documents that match the used to identify documents. Update selector Although MongoDB inserts ID by it’s own, We can manually insert custom IDs as well by specifying parameter in the functions. _id insert...() To insert multiple documents we can use - which takes an array of documents as parameter. When executed, it returns multiple s for each document in the array. To drop the collection, use command. Sometimes, when doing bulk inserts - we may insert duplicate values. Specifically, if we try to insert duplicate s, we’ll get the : insertMany() id drop() _id duplicate key error db.startup.insertMany([{_id:"id1", name:"Uber"},{_id:"id2", name:"Airbnb"},{_id:"id1", name:"Uber"},]); MongoDB stops inserting operation, if it encounters an error, to supress that — we can supply parameter. Ex: ordered:false db.startup.insertMany([{_id:"id1", name:"Uber"},{_id:"id2", name:"Airbnb"},{_id:"id1", name:"Airbnb"},],{ordered: false}); The _id field assigns an field to each document and assigns primary index on it. There’re ways by which we can apply secondary indices as well. By default, creates values for the field of type . This value is defined in spec and it’s structured this way: MongoDB _id MongoDB _id ObjectID BSON ObjectID (12 bytes HEX string) = Date (4 bytes, a timestamp value representing number of seconds since the Unix epoch) + MAC address (3 bytes) + PID (2 bytes) + Counter (3 bytes) Reading documents To apply specific value filters, we can pass specific values to the command. Here is a SQL query: find() SELECT * FROM Table1 WHERE name = 'ABC' which is equivalent to the following in (notice for ): MongoDB Collection1 Table1 db.Collection1.find({name: 'ABC'}) We can chain to get the number of results, to get a readable result. The results can be further narrowed by adding additional parameters: count() pretty() db.Collection1.find({name: 'ABC', rollNo: 5}) It’s important to notice that these filters are ed together, by default. To apply an filter, we need to use . These filters will be specified depending upon the structure of the document. Ex: for object attribute for an object , we need to specify filter like AND OR $or name school "school.name" = 'AUHS' We’re using here the notation, by trying to access a nested field of a field . Also notice that the filters are , without which we’ll get syntax errors. DOT name school quoted Equality matches on arrays can be performed: on the entire arrays based on any element based on a specific element more complex matches using operators In the below query: db.Collection1.find({name: ['ABC','XYZ']}) is going to identify documents by an exact match to an array of one or more values. Now for these types of queries, the of elements matters, meaning that we will only match documents that have by and those are the elements of the array MongoDB order ABC followed XYZ only 2 name {name:["ABC","GHI","XYZ"]}, {name:["DEF","ABC","XYZ"]} In the above document, let’s say that we need to get all the documnts where is the first element. So, we’ll use the below filter: ABC db.Schools.find({'name.0': 'ABC' }) Cursors in MongoDB returns results in batches. To see how many objects are left in a batch, we use like this: MongoDB objLeftInBatch() var c = db.Schools.find();var doc = function() {return c.hasNext()? c.next : null;}c.objLeftInBatch(); To iterate through this batch we can use that we setup in the above code block. More learning on cursors can be found at doc() https://docs.mongodb.com/ Projection in MongoDB Projection is a handy way of reducing the size of the data returned for any one query. By default returns all fields in all documents for queries. To limit the amount of data that sends to the application, we can include projections in the queries to reduce network overhead and processing requirements by limiting the fields that’re returned in results documents. They’re provided as second argument to the command. Now, if we need to limit our documents so that they just contain a title. We can do that using this In the result, is always returned. To exclude it, use . So, to exclude any field, use 0 next to the colon in project query. MongoDB MongoDB find() db.Schools.find({name:"ABC"},{rollNo:1}). _id db.Schools.find({name: "ABC"},{rollNo: 1, _id: 0}). Comparison operators in MongoDB We can use as well in our queries. Eg: Use To find all students having roll number beyond than 10. Notice the operator. Combine this filter with for getting results beyond roll number 10 and before roll number 50: . comparison operators db.Schools.find({rollNo: {$gt: 10}}) [$gt](https://docs.mongodb.com/manual/reference/operator/query/gt/#op._S_gt) $lt db.Schools.find({rollNo: {$gt: 10, $lt: 50}}) There’re other operators as well: (greater than, equal to), (less than, equal to), (not equal to). One thing to notice about the not equal to ( ) operator is that it not only returns documents having value not equal to specified value but also returns documents not having the attribute itself. $gte $lte $ne $ne Element operators in MongoDB because of it’s flexible data model supports operators that allow us to detect the presence of or absence of a given field. This flexibility in terms of data models also extends to the data type of a field value. Because it’s possible although not usually a good idea, to have the same field in a collection have a different type of value from one document to another. These operators are used for finding the existence of elements ( ) and data type of the field using the operator. MongoDB $exists $type Logical operators Like SQL, there’re such as , , and . These’re the examples: logical operators $and $or $not $nor db.Schools.find({$and: [{ rollNo: { $gt: 10 }}, { rollNo: { $gt: 50 }}]}) db.Schools.find({$or: [{ rollNo: { $gt: 10 }}, { rollNo: { $gt: 50 }}]}) Now, why there’s an operator Because, in a document, we cannot have duplicate keys. In the above example, we’re ing twice. Remember that is used we need to filter data on the same field. $and when the filters are by default ed? AND JSON $and AND rollNo $and Regular operators The slashes in the below regex code means the start and end of the regular expression. / The carat means start at the beginning of whatever value we’re matching against and match exactly a capital AB. ^ The dot is the wild card character. . The arterisk indicates match any character any number of times * means a space character after AB \s db.Schools.find({{ name: { $regex: /^AB\s.*/ }}}) These operators are used to work on arrays. For getting matching values from an array ( ), arrays of a particular size ( ) and - which within a single element of an array field. $all $size $elemMatch requires all criteria be satisfied Updating documents provides 3 ways to update documents. MongoDB - the first argument is the filter expression, second specifies the values to be updated updateOne() updateMany() replaceOne() db.Schools.updateOne({ name: "ABC" }, { $set: { rollNo: 15 } }) There are a couple of . In the above query, operator simply replaces (or adds if not already exists) the value for the field being specified. There are as well. To apply updates for each element, use the . modifies the $push operator to specify the position in the array to add elements. update operators $set array update operators array $each $position Sometimes, we might see elements set to . It’s better to remove them altogether using operator. NULL $unset db.Schools.updateMany({ name: null }, { $unset: { name: "" } }) Upserts are operations for which, if no document is found matching our filter, we insert a new document — hence the term . upsert And here we finish second week notes course Photos Originally published at xameeramir.github.io .