Tech Junkie Blog - Real World Tutorials, Happy Coding!: MongoDB In-Depth: Basic MongoDB Commands

Tuesday, November 16, 2021

MongoDB In-Depth: Basic MongoDB Commands

In this post we are going to go over some basic commands that you can run on a machine that has MongoDB installed.

One of the first thing you want to do is to connect to MongoDB so that you can run more commands.
Here is the command to connect to MongoDB

mongo --host=localhost --port=27017

All you need is the name of the host and port number, 27017 is the default port number and since we running the command on the MongoDB host, the host is localhost
















The great thing about MongoDB is that it's easy to insert data, you can pretty much insert data on the fly. Let's say want to create a record mycontacts you can just type

use mycontacts

After typing this you have a db of mycontacts, it's as easy as that





Typing the keyword use will reference db to mycontacts, then to add a contact all you have to do is prefix the contact with db, like so

db.contacts.insert({name: "John", Phones: ["555-555-5555", "666-666-6666"]}) 






That's beauty of MongoDB, it's easy and you can work directly with json, as you may noticed the key does not have quotes around them, that's the difference when you insert the values.   Now let's insert another record

db.contacts.insert({name: "Jane", Phones: ["777-777-7777", "888-888-8888"]}) 

Displaying the data is just as easy, all you have to do is type. Noticed when the data is displayed the quotes are around the key values.  Although quotes are not required for record insertion, it does not mean that you can't it.  mongo just doesn't care.  So can still have "name" and "Phones" as you keys and it would still work.  There is an ObjectId that's specific to Mongo though.

db.contacts.find().pretty()



















Another useful command is the show dbs command, this command will show all the databases in mongo that has data in it









As you can see our mycontacts database is shown because we've added data to it.


Previous: MongoDB In-Depth: Installing MongoDB on Windows



No comments:

Post a Comment

Search This Blog