Learning MongoDB #1 : Document Operations
What Will I Learn?
- You will learn how you can insert, update and remove Documant
- You will learn $set, $unset and $inc operator terms
Requirements
- A working computer running on Windows
- The ambition to learn MongoDB
Difficulty
- Basic / Intermediate
Insert Documents with MongoDB
To insert document we need a database and a collection. We'll use them for insert, update and remove operations. So, firstly we'll create a database and collection. I was talked about it past episode of series. But let's remember it with little example.
As you see firtly I switched to database called vigna
and create two collection called "book"
and "writer"
. Now I can insert document on these collections. Insert()
is basicly a function on MongoDB. We can reach this function on our collection.
db.writer.insert(
{ name: "George", surname: "Martin"})
Via this code we use Insert()
funciton and add a writer name on our writer
collection, George Martin. When we do this, MongoDB shell tell us "we added a new record" with WriteResult
command. Here is our result:
TİP : İf you open a brackets "(" , "{" , "[" and press ENTER, MongoDB shell will understand you trying to write a complex code block and it will act like that to help you.
So, we add two writer on our writer
collection and now we can add books on our book
collection. We follow same process, just changing writer to book.
db.book.insert(
{ name: "Kingdom Come", page: 232})
TİP : İf you want to write an empty page, you can use CTRL+L commands on MongoDB shell.
So, we created our collections and inserted same documents. But how can we list our collections? We can use show collections
or db.getCollectionNames()
commands for this.
As you see, with these commands I can see my all collections. In this contribution we are working on book
and writer
collections and the others are useless, created just for exam. When we use db.getCollectionNames()
command, result will be turn to us Array type. Btw we can reach collections stats with using db.collectionName.stats()
command. For example;
db.writer.stats()
{
"ns" : "vigna.writer",
"size" : 119,
"count" : 2,
"avgObjSize" : 59,
"storageSize" : 32768,
"capped" : false,
.
.
.
This stats is really long so I cut it and take just head part. Because with "count" : 2,
part, we can saw how much document in this collection. The answer is two. We added "George Martin" and "Stan Lee" in the beginning. We can also saw more info about collection on this stats, like storage size etc.
If we need to add more then one record on a collection we can do it like this:
It's very similar to an arraylist. Each document stored in a collection and unique _id
field acts as a primary key.
Update Documents with MongoDB
When we want to update same documents in a collection, we should use update()
fuction. Here is a simple example about how we can use update()
fuction:
db.book.update(
{ _id:1 },
{ name: "Darseid War"}
)
On the first block of update()
fuction, we define a condition for which data we want to update. In this example we said we want to update the record with _id
value 1. We must to be very careful when we work with update()
fuction. Because if you define a wrong condition you can lose your all data. If we want to make multiple updates in a collection we can use $set
command for this.
use vigna
db.createCollection("Amazon")
db.Amazon.insert(
{type:"books", price: "11"}
)
db.Amazon.update(
{type:"books"},
{
$set:{type:"comics", price:"55"}
}
)
As you see, firtly I create a new collection named Amazon and add a new document in it. After this I update document's type and price values. That's how we use $set
operator for multiple updates. But in this scenario first storage wasn't delete. If you want to delete first record storage after update process you should use $unset
operator.
db.Amazon.insert(
{type:"manga", price: "33"}
)
db.Amazon.update(
{_id:3},
{
$unset:{price:""}
}
)
So, we said we don't want to storage price value document which _id
's 3 after update process. So, for now we used $set
and $unset
operators for update a document. But there was another way to do this, $inc
operator.$unset
come from is an abbreviation of increment. In some scenarios we need to reduce and increase some data and for that we can use $inc
operator.
db.Amazon.update(
{price:{$lt:55}},
{
$inc:{price:"1"}
},
{
multi: true
}
)
In this example, we defined a condition on first block of query in update()
function. Our condition work like ifcommand. If price lover then 55 in a document then we'll work on it. Second block of query show us what we will do if this condition will happen. In this example, we increase the price by 1. So, our new price value will be 56.
TİP : $lt command is mean less than. It's a condition.
If we want to drop the price and use document id;
db.Amazon.update(
{_id:2},
{
$inc:{price:"-1"}
}
)
Remove Documents with MongoDB
db.Amazon.remove( {_id:2} )
If we want to remove some values on a document or collection we can use remove()
function for this. For remove condition we should marking which _id
value was one. After remove process we can see how much recod deleted onnRemove
feature of WriteResult
object. If we want to remove all recod on a collection:
db.Amazon.remove( {} )
But if we want to remove only one record for a condition we can add 1 to justOne
parameter. It's very similar with $inc
operator.
db.Amazon.remove(
{ price:{$lt:55}},1 )
Our condition is 'price should be less than 55' because we used $lt
condition.
TİP : db.collection.remove()
function is using for deleting some document in a collection but db.collection.drop()
function is using for deleting a collection.
Your contribution cannot be approved because it does not follow the Utopian Rules.
Need help? Write a ticket on https://support.utopian.io.
Chat with us on Discord.
[utopian-moderator]
Hi @portugalcoin,
I know but @superoo7's tutorial hasn't enough explanation or detailed info for users, especially beginners in my opinion. Also my contrubution isn't an one shot tutorial, a part of series. So, please check again for these situations.
Congratulations @vigna! You have completed some achievement on Steemit and have been rewarded with new badge(s) :
Award for the number of upvotes
Click on any badge to view your own Board of Honor on SteemitBoard.
For more information about SteemitBoard, click here
If you no longer want to receive notifications, reply to this comment with the word
STOP
Congratulations @vigna! You have completed some achievement on Steemit and have been rewarded with new badge(s) :
Award for the number of upvotes
Click on any badge to view your own Board of Honor on SteemitBoard.
For more information about SteemitBoard, click here
If you no longer want to receive notifications, reply to this comment with the word
STOP
Congratulations @vigna! You have completed some achievement on Steemit and have been rewarded with new badge(s) :
Award for the number of upvotes
Click on any badge to view your own Board of Honor on SteemitBoard.
For more information about SteemitBoard, click here
If you no longer want to receive notifications, reply to this comment with the word
STOP
fantastic resource for those interested in learning mongo. as there is a steem mongo database I am tagging #blockchainbi
I am just looking over your account and postings and I am running an experiment here on steemit with the aim of improving retention and the steemit experience and after looking at your account I think it is something you might enjoy. come on over and join in on the discussion
https://steemit.com/steemit/@paulag/let-s-grow-steemit-together-direct-engagement-experiment-week-1
Ouv thank you, of course, I'll join your discussion. I'm glad for this. I want to have new friends and learn new things.