What i learn in MongoDB Basics
Connecting to MongoDB using Mongo
We can connect to MongoDB databases in various ways:
$ mongo simpli_user
$ mongo 192.168.1.100/simpli_user
$ mongo db.yoursimpli.com/simpli_user
$ mongo 192.168.1.100:9999/simpli_user
in this case we are connecting to a database called simpli on localhost, on a remote server, or on a remote server on a different port. When you are connecting to a database, you should see the following.
$ mongo simpli_user
MongoDB shell version: 2.6.7
connecting to: simpli_user
>
Saving information
To save a data, use the JavaScript object and execute the following command:
> db.shelf.save( { name: ‘Shaun Stanislaus’, restaurant_visited : [ ‘Din Tai Feng’, ‘Awfully Chocolate’] })
>
This command saves the data that is usually called “Document” into the collection shelf.
Retrieving information
there are various ways to retrieve the previously stored information:
Fetch the first 10 objects from the simpli_user database (also called a collection), as follows:
> db.shelf.find()
{ “_id” : ObjectId(“4e6bc91a51e10d24db9e4h21"), “name” : “Shaun Stanislaus})
Find by Attributes
db.shelf.find( { name : ‘Shaun Stanislaus’ } )
Find by using regular expressions!
db.shelf.find( { name : /Shaun/ })
Find by using regular expressions using the case-insensitive flag!
db.shelf.find( { name : /shaun/i })
just by adding an i behind the `/`.
Deleting information
To remove all the data from simpli_user, execute the following command:
> db.shelf.remove()
>
To remove a specific data from simpli_user, execute the following command:
> db.shelf.remove({name : `Shaun Stanislaus`})
>
Exporting information using mongoexport
ever wonder how to extract information from MongoDB? It’s mongoexport! The cool thing about Mongo data transfer protocol is all in JSON/BSON formats.
JSON is now a universally accepted and common format of data transfer, you can actually export the database, or the collection, directly in JSON Format — so even your web browser can process data from MongoDB and no more three-tier applications with infinite opportunities.
Here are the basic steps to export data from MongoDB:
$ mongoexport -d simpli_user -c shelf
connected to: 127.0.0.1
{ “_id” : { “$oid” : “4e6bc91a51e10d24db9e4h21" }, “name” : “Shaun Stanislaus”, restaurant_visited : [ ‘Din Tai Feng’, ‘Awfully Chocolate’] }
exported 1 records
exporting to CSV file
$ mongoexport -d simpli_user -c shelf -f name,restaurant_visited —csv -o test.csv
the command saves data in a CSV file and similarly you can export data as a JSON array in the next line.
$ mongoexport -d simpli_user -c shelf —jsonArray
connected to: 127.0.0.1
{ “_id” : { “$oid” : “4e6bc91a51e10d24db9e4h21" }, “name” : “Shaun Stanislaus”, restaurant_visited : [ ‘Din Tai Feng’, ‘Awfully Chocolate’] }]
exported 1 records