Writing your first MongoDB Document
Open your terminal and type mongosh
At this point, you should have mongoDB compass installed on your system. Open this software,
Click on connect
If for any reason you do not have the mongosh instance running, type Services in the search bar
Scroll down and find Mongodb server to be sure that it is running:
if it not, right click on the selection and click start
CREATING A DATABASE
Go to the bottom of your screen on the left panel and click on the + sign
In this lesson, we are going to create a database called bookstore and a collection called books
Please, note that the name of the database is bookstore and the collection is book, so let's stay in SQL the name of the database is bookstore and the name of the table is books. So this is to say that we can have a database without collections but we can not have a collection without a database. You should have this now:
The image above shows that we have books collection in bookstore database and we can create more collections by:
Click on create collection
type the name of the collection
CREATING A DOCUMENT
Click on books and then ADD DATA
Click on Insert Document
{
"title":"Man of Gold",
"author": "Scotchess Whitegg",
"pages": 400,
"genres":["Science", "Fiction"],
"rating": 9
}
When you're done , click insert. Note: ensure you put this in double-quotes
MULTIPLE INSERT
You can add an array of data as a document by:
[
{
"title":"Woman of Steel",
"author": "Scott Cyan",
"pages": 250,
"genres":"Comedy",
"rating": 8.5
} ,
{
"title":"Woman of Gold",
"author": "Scott Purple",
"pages": 250,
"genres":"Anime",
"rating": 8.5
} ,
{
"title":"Woman of Silver",
"author": "Scott Lilac",
"pages": 250,
"genres":"Anime",
"rating": 8.5
} ,
{
"title":"Woman of Bronze",
"author": "Scott Black",
"pages": 250,
"genres":"Anime",
"rating": 8.5
} ,
{
"title":"Woman of Jewel",
"author": "Scott Pink",
"pages": 250,
"genres":"Comedy",
"rating": 8.5
},
{
"title":"Woman",
"author": "Scott Red",
"pages": 250,
"genres":"Adventure",
"rating": 8.5
} ,
{
"title":"Lateness",
"author": "Scott Cream",
"pages": 300,
"genres":"Romance",
"rating": 9.5
} ,
{
"title":"Hello World",
"author": "Scott Steel",
"pages": 900,
"genres":"Technology",
"rating": 7.5
}
]
MODIFY A DOCUMENT
You have four icons to your right to modify the document
- edit - this can be used to update a document.
- copy - this can be used to copy a document.
- clone - this duplicates the document.
- delete - this deletes the document.
FILTER A DOCUMENT
This field can be used to filter all instances of document created in this collection by specifying the key-pair.
if I type:
{rating:6.5}
All instance(s) of rating = 6.5 will be displayed.