ovi.ro

ovi.ro

MongoDB CRUD Operations

MongoDB is a NoSQL database and supports all the classic CRUD ( Create, Read, Update, Delete ) operations.

To perform all this operations you have to select first a database and use the database pointer to select a collection ( collections are tables in the SQL world )

use DatabaseName   // select a database
db.colectionName   // point to a colection in the selected database

You Create stuff with the insert method

db.collection.insert( document|array )

MongoDB automatically creates an “_id” (MongoID) for each record you insert, but you can also specify any unique _id you want. MongoDB drivers generate the MongoID before it sends the insert to the database, so you don’t need to wait for the response to get the lastInsertedId like in SQL databases. See documentation

To Read data from the database you can use the find method

db.collection.find( query, projection )

The query in MongoDB is not an SQL query, but it is an JSON-like object with some special keys for special operations, the simplest example would be something like { key: “value” }. The projection is something similar with the field specification in SQL, by default is like “*”, you wil return the whole document. See documentation

To Update documents from the database you can use upate or save methods

db.collection.update( query, update, options )

The query is a JSON-like match to find the desired data, the update is either a whole document, either an JSON-like object using the special keys $set, $unset key values or $push to array values. The options is an object that can specify if you want multiple updates or insert if no document matched the query.

db.collection.save( document )

Save performs an update if you specify the _id or an insert if you don’t. See documentation

To Delete data you can use the remove method

db.collection.remove( query, justOne )

This deletes use the query to match what you want to delete and a flag for multiple or single deletes (justOne = true means only one delete) See documentation