-
Notifications
You must be signed in to change notification settings - Fork 0
MongoDB Notes
- MongoDB is a BSON/JSON-based document database.
- Each document is a JSON object.
- 'Documents' are kept in 'collections', and a 'database' can have several 'collections'.
- MongoDB enforces no schema, therefore each document may contain a unique set of fields/attributes (even if they are in the same collection).
A MongoDB server's configuration is specified in the '/etc/mongodb.conf' file.
One way to export data from MongoDB is the 'mongoexport' command. Here's an example:
$ mongoexport --host 127.0.0.1 --db mydb --collection customers > customers.json
One way to import data into MongoDB is the 'mongoimport' command. Here's an example:
$ mongoimport -- host 127.0.0.1 --db mydb --collection customers --file customers.json
CRUD is an acronym for Create, Read/Retrieve, Update, and Delete (this basic operations of any database).
The 'save' method/command is used to create documents. You include the text of a JSON document as the parameter. For example:
> db.books.save({ title: "Sixth Column", author: "Heinlein"})
Note: A collection is automatically created when the first document is saved into it.
The 'find' method/command is used to retrieve/read documents. This method/command can be simple and unconditional, or complex and specify criteria and fields to retrieve.
Here is a example of a simple use of the 'find' method/command:
> db.collection.find()
The problem with the output from this command is that it can be hard for a human to read. That is why I suggest appending the 'pretty' method. For example:
> db.collection.find().pretty()
The 'update' method/command is used to modify documents. Usually, the arguments include two JSON Objects. The first JSON Object argument specifies the criteria to identify the document(s) to be modified. The second JSON Object argument specifies how the identified document(s) are to be modified. For example:
> db.collection.update({_id: ObjectId("52aa4ba340920f585c0000c1")}, { $set: { field: "value"})
Note: The '_id' field is automatically added to every document when they are created in MongoDB.
The 'remove' method/command is used to remove documents. While the method could be used without arguments (thereby removing all documents in the identified collection), it is usually used with an argument which specifies the criteria to identify the document(s) to be removed. For example:
> db.collection.remove({_id: ObjectId("52aa4ba340920f585c0000c1")})
Note: You can remove the collection itself by using the 'drop' method. For example:
> dv.collection.drop()