Let’s jump into the world of NoSQL with MongoDB, an open-source, document-oriented database. Instead of rows and tables, MongoDB stores data in flexible, JSON-like documents. This makes it highly scalable and popular for web applications. This guide will show you how to get started using the native drivers for Python and Ruby.
Table of Contents
💻 The MongoDB Document Model
MongoDB’s format is based on JSON (JavaScript Object Notation), where data is stored in key-value pairs. This schemaless approach means that two documents in the same collection (the equivalent of a table) can have different structures. Each document is automatically given a unique _id
field, which acts as its primary key.
💻 Interacting with Python (PyMongo)
The official Python driver for MongoDB is called PyMongo. It provides a simple and intuitive way to connect to your database and manage documents.
- Install the Driver:
pip install pymongo
- Connect and Query:
from pymongo import MongoClient
# Connect to the server
client = MongoClient('localhost', 27017)
# Select the database and collection
db = client.LXF
sampleData = db.sampleData
# Find one document in the collection
item = sampleData.find_one()
print(item)
💻 Interacting with Ruby (mongo-ruby-driver)
The official Ruby driver provides similar functionality for connecting to and interacting with MongoDB.
- Install the Driver (Gem):
gem install mongo
- Connect and Query:
require 'mongo'
include Mongo
# Connect to the server and select the database
client = Mongo::Client.new([ '127.0.0.1:27017'], :database => 'LXF')
# Select the collection
collection = client[:someData]
# Insert multiple documents
500.times do |n|
doc = { :n => n*n }
collection.insert_one(doc)
end
Both drivers make it easy to perform CRUD (Create, Read, Update, Delete) operations. Functions like .insert_one()
, .find()
, .update_many()
, and .delete_one()
are your primary tools for data manipulation.
More Topics
- Redis Guide: The High-Speed In-Memory Data Store
- Riak NoSQL Guide: What’s the Big Deal?
- MongoDB Guide: Build a Blog with Python and Bottle
- MongoDB Guide: An Admin’s Guide to Maximum Power
- MariaDB Guide: The Open Source MySQL Alternative
- SQLite3 Guide: Getting Started with Python
- A Beginner’s Guide to Go: Explore Functions