Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

The Core MongoDB Operations

DZone's Guide to

The Core MongoDB Operations

· Database Zone
Free Resource

Navigating today's database scaling options can be a nightmare. Explore the compromises involved in both traditional and new architectures.

As I mentioned in one of my previous article which aims to create awareness about the NoSQL concept and introduce the populer NoSQL solution MongoDB, the documentation of MongoDB provides sufficient information about how to set up MongoDB to the platform (Linux, Mac os x, Windows) you are using.

If you completed the installation successfully, we can pass from theory to practice. Now we can create our first records by performing the core MongoDB operations ( CRUD operations).

Console

MongoDB is set up by the console application which has all kinds of proficiency for its management. Because MongoDB has no visual tool for management, third-party solutions exist for this purpose. 

First of all, we need to run daemon process for the management of console.  

hakdogan:~ hakdogan$ mongod

After running the shell that will process the data requests in the background for MongoDB by the above command, we must run the mongo JavaScript shell on a new console screen, which was designed for system administrators to make query, crud and other operations on databases. 

hakdogan:~ hakdogan$ mongo

To get help with the help command at this point will be useful for the beginners to see which command makes what kind of operations  

> help
	db.help()                    help on db methods
	db.mycoll.help()             help on collection methods
	sh.help()                    sharding helpers
	rs.help()                    replica set helpers
	help admin                   administrative help
	help connect                 connecting to a db help
	help keys                    key shortcuts
	help misc                    misc things to know
	help mr                      mapreduce

	show dbs                     show database names
	show collections             show collections in current database
	show users                   show users in current database
	show profile                 show most recent system.profile entries with time >= 1ms
	show logs                    show the accessible logger names
	show log [name]              prints out the last segment of log in memory, 'global' is default
	use db_name                  set current database
	db.foo.find()                list objects in collection foo
	db.foo.find( { a : 1 } )     list objects in foo where a == 1
	it                           result of the last line evaluated; use to further iterate
	DBQuery.shellBatchSize = x   set default number of items to display on shell
	exit                         quit the mongo shell

First, let's look at the list of existing databases that comes with setup. 

> show dbs
local	0.078125GB

Let’s determine a usage scenario now, and then create a database that will host the collections where we will make crud operations. 

Scenario

Saving articles published in kodcu.com as documents ( don’t forget, each record in MongoDB is a document indeed ) that have category, title, content, date, author, tag fields; making query, update and delete operations on the fields of these documents.  

> use kodcu
switched to db kodcu

In MongoDB, there is not a create command to create a database similar to conventional sql databases. We already do not need such a thing because MongoDB makes the create operation when you add any record to the defined database. We have carried out the process of defining database by the above use kodcu command. As can be seen from the output, we can also make choices among the existing databases by the use command. 

> article  = {
              category: ["Articles"], 
              title: "Lean Kanban Workshop", 
              content: " Kanban system is an impressive approach in the field of software management for the last 10 years.", 
              date: new Date('2013-04-11'), 
              author: "Altuğ Bilgin Altıntaş", 
              tags: [null]}
{
	"category" : ["Articles"],
	"title" : "Lean Kanban Workshop",
	"content" : " Kanban system is an impressive approach in the field of software management for the last 10 years.",
	"date" : ISODate("2013-04-11T00:00:00Z"),
	"author" : "Altuğ Bilgin Altıntaş",
	"tags" : [null]
}
> db.articles.save(article)

We created articles collection ( As I mentioned in the previous article, collections in MongoDB correspond to the tables in sql world)  in the kodcu database by db.articles.save(article) command and added the previously defined article object to this collection. Thus, we have added our first record (document) to MongoDB.

We get the same result with the following command. 

db.articles.insert({
                   category: [“Yazılar”], 
                   title: "Lean Kanban Workshop", 
                   content: " Kanban system is an impressive approach in the field of software management for the last 10 years.", 
                   date: new Date('2013-04-11'), 
                   author: "Altuğ Bilgin Altıntaş", 
                   tags: [null]})

> show dbs
kodcu	0.203125GB
local	0.078125GB
> show collections
articles
system.indexes
> db.articles.find()
{ "_id" : ObjectId("516a93d0b26184f91a8b985c"), 
  "category" : [ "Articles" ], 
  "title" : "Lean Kanban Workshop", 
  "content" : " Kanban system is an impressive approach in the field of software management for the last 10 years.", 
  "date" : ISODate("2013-04-11T00:00:00Z"), 
  "author" : "Altuğ Bilgin Altıntaş", 
  "tags" : [ null ] 
}

As can be seen, a kodcu database and an articles collection in this database are formed. We output the records in the related collection by making a find() call on collection. A value here that we did not enter it manually may draw your attention, I mean id value.

Each document in MongoDB has an unique ID field. We mean the _id field here. If any value is not assigned to _id field manually, MongoDB assigns an ObjectId type unique identification value. 

We entered a null value to the tag field in the first record we created, now let’s update this field.  

> db.articles.update({_id:ObjectId("516a93d0b26184f91a8b985c")}, 
                     {$set: {"tags": ["lean","kanban","training"]}})
> db.articles.find()
{ "_id" : ObjectId("516a93d0b26184f91a8b985c"), 
  "author" : "Altuğ Bilgin Altıntaş", 
  "category" : [ "Articles" ], 
  "content" : "Kanban system is an impressive approach in the field of software management for the last 10 years.", 
  "date" : ISODate("2013-04-11T00:00:00Z"), 
  "tags" : [ "lean", "kanban", "training" ], 
  "title" : "Lean Kanban Workshop" 
}

Let’s add new records now and see how to run queries on these records.  

>db.articles.insert({
                    category: ["Articles"], 
                    title: "Take the reins with Backbone.js! – Free Webiner", 
                    content: "Backbone.js is a JavaScript library that helps your complicated Javascript code to be more structured and offers an environment in which development  is more pleasant.", 
                    date: new Date('2013-04-10'), 
                    author: "Kodcu.Com", 
                    tags: [null]})

>db.articles.insert({
                    category: ["Java", "Tutorial", "Articles", "Software"], 
                    title: "Data Indexing with Java to Apache", 
                    content: "Hi all, I mentioned in my previous article the installation and configuration of Apache Solr, data indexing from command line to Solr and making query operations through this data.", 
                    date: new Date('2013-04-09'), 
                    author: "Cüneyt Yeşilkaya", 
                    tags: ["java", "data indexing with java to solr", "solr", "solrj"]})

>db.articles.insert({
                    category: ["NoSQL", "Yazılar"], 
                    title: "The Core MongoDB Operations", 
                    content: "By creating awareness about the concept of NoSQL...", 
                    date: new Date('2013-04-15'), 
                    author: "Hüseyin Akdoğan", 
                    tags: ["mongodb", "nosql"]})

Let’s find the articles written by Altuğ Bilgin Altıntaş in the current records.  

> db.articles.find({author: "Altuğ Bilgin Altıntaş"})
{ "_id" : ObjectId("516a93d0b26184f91a8b985c"), 
  "author" : "Altuğ Bilgin Altıntaş", 
  "category" : [ "Articles" ], 
  "content" : "Kanban system is an impressive approach in the field of software management for the last 10 years.", 
  "date" : ISODate("2013-04-11T00:00:00Z"), 
  "tags" : [ "lean", "kanban", "training" ], 
  "title" : "Lean Kanban Workshop" 
}

In here, we have seen how to make query according to the desired field and this feature is one of the point that makes MongoDB different and highlighting from other NoSQL solutions as I mentioned before. Under the same title, I also mentioned MongoDB offers its users to benefit from ( regular expressions) in queries. In this context, when we want to find out the articles that have Backbone and JavaScript statements in their contents, we should use a syntax like this. 

> db.articles.find({content: {$regex: 'Backbone.*JavaScript'}})
{ "_id" : ObjectId("516a9432b26184f91a8b985d"), 
  "category" : [ "Articles" ], 
  "title" : "Take the reins with Backbone.js! – Free Webiner", 
  "content" : "Backbone.js is a JavaScript library that helps your complicated Javascript code to be more structured and offers an environment in which development  is more pleasant.", 
  "date" : ISODate("2013-04-10T00:00:00Z"), 
  "author" : "Kodcu.Com", 
  "tags" : [ null ] 
}

MongoDB offers quite useful 4 choices when using regular expressions.  One of them is used for upper and lower case insensitive queries.  

> db.articles.find({content: {$regex: 'backbone.*javascript', $options: 'i'}})
{ "_id" : ObjectId("516a9432b26184f91a8b985d"), 
  "category" : [ "Articles" ], 
  "title" : "Take the reins with Backbone.js! – Free Webiner", 
  "content" : "Backbone.js is a JavaScript library that helps your complicated Javascript code to be more structured and offers an environment in which development  is more pleasant.", 
  "date" : ISODate("2013-04-10T00:00:00Z"), 
  "author" : "Kodcu.Com", 
  "tags" : [ null ] 
}

Finally, let’s see how to delete a record. 

> db.articles.find()
{ "_id" : ObjectId("516a93d0b26184f91a8b985c"), 
  "author" : "Altuğ Bilgin Altıntaş", 
  "category" : [ "Articles" ], 
  "content" : "Kanban system is an impressive approach in the field of software management for the last 10 years.", 
  "date" : ISODate("2013-04-11T00:00:00Z"), 
  "tags" : [ "lean", "kanban", "training" ], 
  "title" : "Lean Kanban Workshop" 
}
{ "_id" : ObjectId("516a9432b26184f91a8b985d"), 
  "category" : [ "Articles" ], 
  "title" : "Take the reins with Backbone.js! – Free Webiner", 
  "content" : "Backbone.js is a JavaScript library that helps your complicated Javascript code to be more structured and offers an environment in which development  is more pleasant.", 
  "date" : ISODate("2013-04-10T00:00:00Z"), 
  "author" : "Kodcu.Com", 
  "tags" : [ null ] 
}
{ "_id" : ObjectId("516a943bb26184f91a8b985e"), 
  "category" : [ "Java", "Tutorial", "Articles", "Software" ], 
  "title" : "Data Indexing with Java to Apache Solr’a Veri", 
  "content" : " Hi all, I mentioned in my previous article the installation and configuration of Apache Solr, data indexing from command line to Solr and making query operations through this data..", 
  "date" : ISODate("2013-04-09T00:00:00Z"), 
  "author" : "Cüneyt Yeşilkaya", 
  "tags" : [ "java", "data indexing with java to solr", "solr", "solrj" ] 
}
{ "_id" : ObjectId("516a9444b26184f91a8b985f"), 
  "category" : [ "NoSQL", "Articles" ], 
  "title" : "The Core MongoDB Operations", 
  "content" : " By creating awareness about the concept of NoSQL...", 
  "date" : ISODate("2013-04-15T00:00:00Z"), 
  "author" : "Hüseyin Akdoğan", 
  "tags" : [ "mongodb", "nosql" ] 
}

> db.articles.remove({_id:ObjectId("516a9444b26184f91a8b985f")})

The operations we discussed and made through the console here are also possible to be performed by the software languages that MongoDB makes drive support. If all being well, I want to discuss how to carry out similar operations done here with MongoDB provided native java driver in the next tutorial.

Real content above, can be accessed at  The Core MongoDB Operations 

Understand your options for deploying a database across multiple data centers - without the headache.

Topics:

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}