# <center><i class="fa fa-edit"></i> Navigating MongoDB: Creating and Manipulating Documents </center> ###### tags: `Internship` :::info **Goal:** To gain a basic understanding of MongoDB fundamentals. Focus on creating and manipulating documents. - [x] Inserting Documents - [x] Updating Documents - [x] Deleting Documents **Resources:** [MongoDB Basics Online Course](https://university.mongodb.com/courses/M001/about) [MongoDB 常用Query指令](/b2Y7lgR1RaeQyMHp9RGHdQ) [Database Commands](https://www.mongodb.com/docs/manual/reference/command/) ::: ## Overview - Every document must have a `unique_id `value - `ObjectID()`: Default value for the `_id` field unless otherwise stated ### Inserting New Documents If a document is inserted without a provided _id value, then the _id field and value will be automatically generated for the inserted document before insertion. - Import Atlas Cluster ``` mongoimport --uri="mongodb+srv://<username>:<password>@<cluster>.mongodb.net/sample_supplies" sales.json ``` - Connect to Atlas Cluster ``` mongo "mongodb+srv://<username>:<password>@<cluster>.mongodb.net/admin" ``` - Navigate to database ``` use sample_training ``` - `findOne()`: Get random document from collection ``` db.inspections.findOne(); ``` - Insert document ``` db.inspections.insert({ "id" : "10021-2015-ENFO", "certificate_number" : 9278806, "business_name" : "ATLIXCO DELI GROCERY INC.", "date" : "Feb 20 2015", "result" : "No Violation Issued", "sector" : "Cigarette Retail Dealer - 127", "address" : { "city" : "RIDGEWOOD", "zip" : 11385, "street" : "MENAHAN ST", "number" : 1712 } }) ``` - `find()` ``` db.inspections.find({"id" : "10021-2015-ENFO", "certificate_number" : 9278806}).pretty() ``` - `findOne()`: queries by `_id` - `findMany()`: queries all ### Inserting Multiple Documents When many documents are inserted, the default behavior is to insert them in the order in which they are listed in the array. If you insert documents into a non-existent database, the database will be created for you. - Insert three test documents ``` db.inspections.insert([ { "test": 1 }, { "test": 2 }, { "test": 3 } ]) ``` - Insert three test documents to try out duplicate ID error. Result: Only the first test is inserted and duplicate ID error is produced. ``` db.inspections.insert([{ "_id": 1, "test": 1 },{ "_id": 1, "test": 2 },{ "_id": 3, "test": 3 }]) ``` - Insert three test documents to try out duplicate ID error specifying `{"ordered: false"}`. Result: Both first and third test are inserted and duplicate ID error is produced. ``` db.inspections.insert([{ "_id": 1, "test": 1 },{ "_id": 1, "test": 2 },{ "_id": 3, "test": 3 }], {"ordered: false"}) ``` - Find the documents with `_id: 1` ``` db.inspections.find({ "_id": 1 }) ``` - View collections in the active db ``` show collections ``` - Switch the active db to training ``` use training ``` - View all available databases ``` show dbs ``` ### Updating Documents **Update Operators** - `$inc`: Increments field value by a specified amount - `$set`: Sets field value to a new specified value - `$unset`: Deletes a particular field - `$push`: Adds an element to an arrat field - `updateOne()`: queries by `_id` - `updateMany()`: queries all **Procedures** - Connect to Atlas Cluster ``` mongo "mongodb+srv://<username>:<password>@<cluster>.mongodb.net/admin" ``` - Navigate to database ``` use sample_training ``` - Find all documents in the `zips` collection where the `zip` field is equal to `"12434"` ``` db.zips.find({ "zip": "12534" }).pretty() ``` - Find all documents in the `zips` collection where the `city` field is equal to `"HUDSON"` ``` db.zips.find({ "city": "HUDSON" }).pretty() ``` - Find how many documents in the `zips` collection have the `city` field equal to `"HUDSON"` ``` db.zips.find({ "city": "HUDSON" }).count() ``` - Update all documents in the `zips` collection where the `city` field is equal to `"HUDSON"` by adding `10` to the current value of the `"pop"` field ``` db.zips.updateMany({ "city": "HUDSON" }, { "$inc": { "pop": 10 } }) ``` - Update a single document in the `zips` collection where the `zip` field is equal to `"12534" `by setting the value of the `"pop"` field to `17630` ``` db.zips.updateOne({ "zip": "12534" }, { "$set": { "pop": 17630 } }) ``` - Update a single document in the `zips` collection where the `zip` field is equal to `"12534" `by setting the value of the `"population"` field to `17630` ``` db.zips.updateOne({ "zip": "12534" }, { "$set": { "population": 17630 } }) ``` - Find all documents in the `grades` collection where the `student_id` field is `151` , and the `class_id` field is `339` ``` db.grades.find({ "student_id": 151, "class_id": 339 }).pretty() ``` - Find all documents in the `grades` collection where the `student_id` field is `250`, and the class_id field is `339` ``` db.grades.find({ "student_id": 250, "class_id": 339 }).pretty() ``` - Update one document in the grades collection where the `student_id` is `250`, and the `class_id` field is `339`, by adding a document element to the `"scores"` array ``` db.grades.updateOne({ "student_id": 250, "class_id": 339 }, { "$push": { "scores": { "type": "extra credit", "score": 100 } } }) ``` ### Deleting Documents and Collections Removing all collections in a database also remove the database **Delete Operators** - `deleteOne()`: queries by `_id` to delete a database - `deleteMany()`: queries all to delete a database - `drop()`: removes an entire collection from a database **Procedures** - Connect to Atlas Cluster and Navigate to Database ``` mongo "mongodb+srv://<username>:<password>@<cluster>.mongodb.net/admin" use sample_training ``` - Look at all the docs that have test field equal to 1 ``` db.inspections.find({ "test": 1 }).pretty() ``` - Look at all the docs that have test field equal to 3 ``` db.inspections.find({ "test": 3 }).pretty() ``` - Delete all the documents that have test field equal to 1 ``` db.inspections.deleteMany({ "test": 1 }) ``` - Delete one document that has test field equal to 3 ``` db.inspections.deleteOne({ "test": 3 }) ``` - Inspect what is left of the inspection collection ``` db.inspection.find().pretty() ``` - View what collections are present in the sample_training collection ``` show collections ``` - Drop the inspection collection ``` db.inspection.drop() ```