MongoDB is the document database designed to make it easy for developers to work with data in any form, and from any programming language. Whether you’re just firing up your first MongoDB Atlas cluster, or you’re a long-time veteran user, we put together our best set of useful examples to refresh your knowledge or help you get your bearings. Don’t hesitate to go over to the official documentation for more in-depth discussions of all of these topics.
Structuring Document Data
MongoDB documents are formatted in BSON (an extended Binary form of JSON) , which allows you ultimate flexibility in structuring data of all types. Below are just a few of the ways you can structure your documents.
Storing Nested Data Structures
Perhaps the most powerful feature of document databases is the ability to nest objects inside of documents. A good rule of thumb for structuring data in MongoDB is to prefer embedding data inside documents to breaking it apart into separate collections, unless you have a good reason (like needing to store unbounded lists of items, or needing to look up objects directly without retrieving a parent document).
{_id: ObjectId("5effaa5662679b5af2c58829"),
email: “email@example.com”,
name: {given: “Jesse”, family: “Xiao”},
age: 31,
addresses: [{label: “home”,
street: “101 Elm Street”,
city: “Springfield”,
state: “CA”,
zip: “90000”,
country: “US”},
{label: “mom”,
street: “555 Main Street”,
city: “Jonestown”,
province: “Ontario”,
country: “CA”}]
}
Note that the name field is a nested object containing both given and family name components, and that the addresses field stores an array containing multiple addresses. Each address can have different fields in it, which makes it easy to store different types of data.
Using the MongoDB Shell
The MongoDB shell is a great tool for navigating, inspecting, and even manipulating document data. If you’re running MongoDB on your local machine, firing up the shell is as simple as typing mongo and hitting enter, which will connect to MongoDB at localhost on the standard port (27017). If you’re connecting to a MongoDB Atlas cluster or other remote instance, then add the connection string after the command mongo
Here are a few quick shell examples:
List Databases
> show dbs;
admin 0.000GB
config 0.000GB
local 0.000GB
my_database 0.004GB
>
List Collections
> use my_database;
> show collections;
users
posts
>
Count Documents in a Collection
> use my_database;
> db.users.count()
20234
>
Find the First Document in a Collection
> db.users.findOne()
{
"_id": ObjectId("5ce45d7606444f199acfba1e"),
"name": {given: "Alex", family: "Smith"},
"email": "email@example.com"
"age": 27
}
>
Find a Document by ID
> db.users.findOne({_id: ObjectId("5ce45d7606444f199acfba1e")})
{
"_id": ObjectId("5ce45d7606444f199acfba1e"),
"name": {given: "Alex", family: "Smith"},
"email": "email@example.com",
"age": 27
}
>
Querying MongoDB Collections
The MongoDB Query Language (MQL) uses the same syntax as documents, making it intuitive and easy to use for even advanced querying. Let’s look at a few MongoDB query examples.
Find a Limited Number of Results
> db.users.find().limit(10)
…
>
Find Users by Family name
> db.users.find({"name.family": "Smith"}).count()
1
>
Note that we enclose “name.family” in quotes, because it has a dot in the middle.
Query Documents by Numeric Ranges
// All posts having “likes” field with numeric value greater than one:
> db.post.find({likes: {$gt: 1}})
// All posts having 0 likes
> db.post.find({likes: 0})
// All posts that do NOT have exactly 1 like
> db.post.find({likes: {$ne: 1}})
Sort Results by a Field
// order by age, in ascending order (smallest values first)
> db.user.find().sort({age: 1})
{
"_id": ObjectId("5ce45d7606444f199acfba1e"),
"name": {given: "Alex", family: "Smith"},
"email": "email@example.com",
"age": 27
}
{
_id: ObjectId("5effaa5662679b5af2c58829"),
email: “email@example.com”,
name: {given: “Jesse”, family: “Xiao”},
age: 31
}
>
// order by age, in descending order (largest values first)
> db.user.find().sort({age: -1})
{
_id: ObjectId("5effaa5662679b5af2c58829"),
email: “email@example.com”,
name: {given: “Jesse”, family: “Xiao”},
age: 31
}
{
"_id": ObjectId("5ce45d7606444f199acfba1e"),
"name": {given: "Alex", family: "Smith"},
"email": "email@example.com",
"age": 27
}
>
Managing Indexes
MongoDB allows you to create indexes, even on nested fields in subdocuments, to keep queries performing well even as collections grow very large.
Create an Index
> db.user.createIndex({"name.family": 1})
Create a Unique Index
> db.user.createIndex({email: 1}, {unique: true})
Unique indexes allow you to ensure that there is at most one record in the collection with a given value for that field – very useful with things like email addresses!
See Indexes on a Collection
> db.user.getIndexes()
[
{
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "my_database.user"
},
{
"v" : 2,
"key" : {
"name.given" : 1
},
"name" : "name.given_1",
"ns" : "my_database.user"
}
]
Note that by default, collections always have an index on the _id field, for easy document retrieval by primary key, so any additional indexes will be listed after that.
Drop an Index
> db.user.dropIndex("name.given_1")
Conclusion
The ultimate flexibility of MongoDB means that this is far from a comprehensive list of everything you can do with it! For more information, head over to the MongoDB documentation, or take a course a MongoDB University.
Related Content:
- MongoDB University Course - M201: MongoDB Performance
- How to create a database in MongoDB
- Embedding documents in MongoDB
- What is replication in MongoDB?
- Using ACID transactions in MongoDB
- What is the MEAN stack?