Linux:Powerful Server Administration
上QQ阅读APP看书,第一时间看更新

Storing and retrieving data with MongoDB

In this recipe, we will look at basic CRUD operations with MongoDB. We will learn how to create databases, store, retrieve, and update stored data. This is a recipe to get started with MongoDB.

Getting ready

Make sure that you have installed and configured MongoDB. You can also use the MongoDB installation on a remote server.

How to do it…

Follow these steps to store and retrieve data with MongoDB:

  1. Open a shell to interact with the Mongo server:
    $ mongo
    
  2. To open a shell on a remote server, use the command given. Replace server_ip and port with the respective values:
    $ mongo server_ip:port/db
    
  3. To create and start using a new database, type use dbname. Since schemas in MongoDB are dynamic, you do not need to create a database before using it:
    > use testdb
    
  4. You can type help in Mongo shell to get a list of available commands and help regarding a specific command:

    > help: Let’s insert our first document:

    > db.users.insert({‘name’:’ubuntu’,’uid’:1001})
    
  5. To view the created database and collection, use the following commands:
    > show dbs
    
    > show collections
    
  6. You can also insert multiple values for a key, for example, which groups a user belongs to:
    > db.users.insert({‘name’:’root’,’uid’:1010, ‘gid’:[1010, 1000, 1111]})
    
  7. Check whether a document is successfully inserted:
    > db.users.find()
    
  8. To get a single record, use findOne():
    > db.users.findOne({uid:1010})
    
  9. To update an existing record, use the update command as follows:
    > db.users.update({name:’ubuntu’}, {$set:{uid:2222}})
    
  10. To remove a record, use the remove command. This will remove all records with a name equal to ubuntu:
    > db.users.remove({‘name’:’ubuntu’})
    
  11. To drop an entire collection, use the drop() command:
    > db.users.drop()
    
  12. To drop a database, use the dropDatabase() command:
    > db.users.dropDatabase()
    

How it works…

The preceding examples show very basic CRUD operations with the MongoDB shell interface. MongoDB shell is also a JavaScript shell. You can execute all JS commands in a MongoDB shell. You can also modify the shell with the configuration file, ~/.mongorc.js. Similar to shell, MongoDB provides language-specific drivers, for example, MongoDB PHP drivers to access MongoDB from PHP.

MongoDB works on the concept of collections and documents. A collection is similar to a table in MySQL and a document is a set of key value stores where a key is similar to a column in a MySQL table. MongoDB does not require any schema definitions and accepts any pair of keys and values in a document. Schemas are dynamically created. In addition, you do not need to explicitly create the collection. Simply type a collection name in a command and it will be created if it does not already exist. In the preceding example, users is a collection we used to store all data. To explicitly create a collection, use the following command:

> use testdb
> db.createCollection(‘users’)

You may be missing the where clause in MySQL queries. We have already used that with the findOne() command:

> db.users.findOne({uid:1010})

You can use $lt for less than, $lte for less than or equal to, $gt for greater than, $gte for greater than or equal to, and $ne for not equal:

> db.users.findOne({uid:{$gt:1000}})

In the preceding example, we have used the where clause with the equality condition uid=1010. You can add one more condition as follows:

> db.users.findOne({uid:1010, name:’root’})

To use the or condition, you need to modify the command as follows:

> db.users.find ({$or:[{name:’ubuntu’}, {name:’root’}]})

You can also extract a single key (column) from the entire document. The find command accepts a second optional parameter where you can specify a select criteria. You can use values 1 or 0. Use 1 to extract a specific key and 0 otherwise:

> db.users.findOne({uid:1010}, {name:1})
> db.users.findOne({uid:1010}, {name:0})

There’s more…

You can install a web interface to manage the MongoDB installation. There are various open source web interfaces listed on Mongo documentation at http://docs.mongodb.org/ecosystem/tools/administration-interfaces/.

When you start a mongo shell for the first time, you may see a warning message regarding transperent_hugepage and defrag. To remove those warnings, add the following lines to /etc/init/mongod.conf, below the $DAEMONUSER /var/run/mongodb.pid line:

if test -f /sys/kernel/mm/transparent_hugepage/enabled; then
  echo never > /sys/kernel/mm/transparent_hugepage/enabled
fi
if test -f /sys/kernel/mm/transparent_hugepage/defrag; then
  echo never > /sys/kernel/mm/transparent_hugepage/defrag
fi

Find more details on this Stack Overflow post at http://stackoverflow.com/questions/28911634/how-to-avoid-transparent-hugepage-defrag-warning-from-mongodb

See also