Navigation

Getting Started

MongoDB Atlas is a cloud-hosted service for provisioning, running, monitoring, and maintaining MongoDB deployments. It is a fast, easy, and free way to get started with MongoDB. To install and run MongoDB locally, see Install MongoDB.

To learn more about the MongoDB query language and other MongoDB fundamentals, sign up for M001: MongoDB Basics.

1

Create an Atlas user account.

To get started with MongoDB Atlas, create your user account and log in to Atlas.

2

Create an Atlas Group.

Choose a name for your group.

Screenshot of group creation prompt.

Groups manage related MongoDB deployments. To create additional Atlas groups, click on your user name in the upper-right hand corner and select My Groups. Click the Add Group button.

3

Create a cluster.

MongoDB deployments, or “clusters” in Atlas, can be either a replica set or a sharded cluster.

To create a cluster, go to the Clusters view and click the Add New Cluster or Build a New Cluster button.

Screenshot of cluster config options during creation.
  1. Enter a Cluster Name.

  2. Click the Select button for Instance Size M0 for Atlas Free Tier.

  3. Enter a Username and Password.

    Screenshot of admin username and password fields that appear only when admin user doesn't exist.

    These fields appear only if no MongoDB user exists for your Atlas group. If you created users in the group beforehand these fields will not appear.

  4. Click Confirm & Deploy.

4

Setup security.

Atlas only allows client connections to the cluster from entries in the group’s whitelist. To add an entry to the whitelist:

Screeenshot of cluster security tab on Atlas.
  1. Click the Security tab from the Clusters view.
  2. Click IP Whitelist, then Add IP Address. You may either enter the IP address manually in the Whitelist Entry field or click the Add Current IP Address button.
  3. Click Confirm and wait for Atlas to update the firewall.
5

Download the connecting client.

To download the mongo Shell:

  1. Click the Connect button from the Clusters view.
  2. Under the Connect with the Mongo Shell section, select your operating system from the dropdown and click Download Shell.
  3. Extract the download to the desired location or install the mongo shell depending on your operating system.
  4. Optionally, add the <mongodb-install-directory>/bin to your operating system’s PATH or environment variables.

For more operating system specific installation information, see Installation.

Install the PyMongo driver via pip:

python -m pip install pymongo

For more information, see Installing Pymongo.

First create your project using npm init then install the MongoDB Node.js Driver via npm:

npm install mongodb --save

For more information, see the Node.js driver Quick Start documentation.

6

Get the URI connection string.

From the MongoDB Atlas Clusters view:

  1. Click the Connect button to view the URI Connection String.
  2. Copy the connection string to the clipboard.
  3. Paste the connection string somewhere and replace <PASSWORD> with the password for the user created earlier, and <DATABASE> with the name of the database to which you wish to connect. In the following examples, the test database is used.
7

Connect to the cluster.

Using the URI string from the previous step, connect to the Atlas cluster:

<mongodb-install-directory>/bin/mongo "mongodb://user123:p455w0rd@gettingstarted-shard-00-00-hyjsm.mongodb.net:27017,gettingstarted-shard-00-01-hyjsm.mongodb.net:27017,gettingstarted-shard-00-02-hyjsm.mongodb.net:27017/test?ssl=true&replicaSet=GettingStarted-shard-0&authSource=admin"

Alternatively, if you added <mongodb-install-directory>/bin to the PATH then you may run:

mongo "mongodb://user123:p455w0rd@gettingstarted-shard-00-00-hyjsm.mongodb.net:27017,gettingstarted-shard-00-01-hyjsm.mongodb.net:27017,gettingstarted-shard-00-02-hyjsm.mongodb.net:27017/test?ssl=true&replicaSet=GettingStarted-shard-0&authSource=admin"

For Windows, run:

"C:\Program Files\MongoDB\Server\3.4\bin\mongo.exe" "mongodb://user123:p455w0rd@gettingstarted-shard-00-00-hyjsm.mongodb.net:27017,gettingstarted-shard-00-01-hyjsm.mongodb.net:27017,gettingstarted-shard-00-02-hyjsm.mongodb.net:27017/test?ssl=true&replicaSet=GettingStarted-shard-0&authSource=admin"
from pymongo import MongoClient

client = pymongo.MongoClient("mongodb://user123:p455w0rd@gettingstarted-shard-00-00-hyjsm.mongodb.net:27017,gettingstarted-shard-00-01-hyjsm.mongodb.net:27017,gettingstarted-shard-00-02-hyjsm.mongodb.net:27017/test?ssl=true&replicaSet=GettingStarted-shard-0&authSource=admin")
db = client.test

# Paste the following examples here
var MongoClient = require('mongodb').MongoClient;

var uri = "mongodb://user123:p455w0rd@gettingstarted-shard-00-00-hyjsm.mongodb.net:27017,gettingstarted-shard-00-01-hyjsm.mongodb.net:27017,gettingstarted-shard-00-02-hyjsm.mongodb.net:27017/test?ssl=true&replicaSet=GettingStarted-shard-0&authSource=admin";
MongoClient.connect(uri, function(err, db) {
  // Paste the following examples here

  db.close();
});

Documents and Collections

MongoDB stores data as BSON documents (binary represenatation of JSON) in collections. MongoDB databases hold collections of documents.

Insert Documents

db.collection.insertMany() can insert multiple documents into a collection. Pass an array of documents to the method.

The following example inserts new documents into the inventory collection:

db.inventory.insertMany([
   // MongoDB adds the _id field with an ObjectId if _id is not present
   { item: "journal", qty: 25, status: "A",
       size: { h: 14, w: 21, uom: "cm" }, tags: [ "blank", "red" ] },
   { item: "notebook", qty: 50, status: "A",
       size: { h: 8.5, w: 11, uom: "in" }, tags: [ "red", "blank" ] },
   { item: "paper", qty: 100, status: "D",
       size: { h: 8.5, w: 11, uom: "in" }, tags: [ "red", "blank", "plain" ] },
   { item: "planner", qty: 75, status: "D",
       size: { h: 22.85, w: 30, uom: "cm" }, tags: [ "blank", "red" ] },
   { item: "postcard", qty: 45, status: "A",
       size: { h: 10, w: 15.25, uom: "cm" }, tags: [ "blue" ] }
]);

insertMany() returns a document that includes the newly inserted documents _id field values. See the reference for an example.

Use db.collection.insertOne() to insert a single document.

pymongo.collection.Collection.insert_many() can insert multiple documents into a collection. Pass an array of documents to the method.

The following example inserts new documents into the inventory collection:

db.inventory.insert_many([
   # MongoDB adds the _id field with an ObjectId if _id is not present
   { "item": "journal", "qty": 25, "status": "A",
       "size": { "h": 14, "w": 21, "uom": "cm" }, "tags": [ "blank", "red" ] },
   { "item": "notebook", "qty": 50, "status": "A",
       "size": { "h": 8.5, "w": 11, "uom": "in" }, "tags": [ "red", "blank" ] },
   { "item": "paper", "qty": 100, "status": "D",
       "size": { "h": 8.5, "w": 11, "uom": "in" }, "tags": [ "red", "blank", "plain" ] },
   { "item": "planner", "qty": 75, "status": "D",
       "size": { "h": 22.85, "w": 30, "uom": "cm" }, "tags": [ "blank", "red" ] },
   { "item": "postcard", "qty": 45, "status": "A",
       "size": { "h": 10, "w": 15.25, "uom": "cm" }, "tags": [ "blue" ] }
])

insert_many() returns a document that includes the newly inserted documents _id field values. See the reference for an example.

Use pymongo.collection.Collection.insert_one() to insert a single document.

Collection.insertMany() can insert multiple documents into a collection. Pass an array of documents to the method.

The following example inserts new documents into the inventory collection:

db.collection('inventory').insertMany([
   // MongoDB adds the _id field with an ObjectId if _id is not present
   { item: "journal", qty: 25, status: "A",
       size: { h: 14, w: 21, uom: "cm" }, tags: [ "blank", "red" ] },
   { item: "notebook", qty: 50, status: "A",
       size: { h: 8.5, w: 11, uom: "in" }, tags: [ "red", "blank" ] },
   { item: "paper", qty: 100, status: "D",
       size: { h: 8.5, w: 11, uom: "in" }, tags: [ "red", "blank", "plain" ] },
   { item: "planner", qty: 75, status: "D",
       size: { h: 22.85, w: 30, uom: "cm" }, tags: [ "blank", "red" ] },
   { item: "postcard", qty: 45, status: "A",
       size: { h: 10, w: 15.25, uom: "cm" }, tags: [ "blue" ] }
])
.then(function(result) {
  // process result
})

insertMany() returns a document that includes the newly inserted documents _id field values. See the reference for an example.

Use Collection.insertOne() to insert a single document.

For more information and examples, see Insert Documents in the CRUD section.

Query Documents

Select All Documents

To select all documents in the collection, pass an empty document as the query filter document to the db.collection.find() method:

To select all documents in the collection, pass an empty document as the query filter document to the pymongo.collection.Collection.find() method:

To select all documents in the collection, pass an empty document as the query filter document to the Collection.find() method:

db.inventory.find( {} )
cursor = db.inventory.find({})
FindIterable<Document> findIterable = collection.find(new Document());
var cursor = db.collection('inventory').find({});
$cursor = $db->inventory->find([]);
$cursor = $db->coll("inventory")->find( {} );
client[:inventory].find({})
var findObservable = collection.find(Document())
var filter = Builders<BsonDocument>.Filter.Empty;
var result = collection.Find(filter).ToList();

To query for documents that match specific equality conditions, pass the find() method a query filter document with the <field>: <value> of the desired documents. The following example selects from the inventory collection all documents where the status equals "D":

To query for documents that match specific equality conditions, pass the find() method a query filter document with the <field>: <value> of the desired documents. The following example selects from the inventory collection all documents where the status equals "D":

To query for documents that match specific equality conditions, pass the find() method a query filter document with the <field>: <value> of the desired documents. The following example selects from the inventory collection all documents where the status equals "D":

db.inventory.find( { status: "D" } )
cursor = db.inventory.find({"status": "D"})
findIterable = collection.find(eq("status", "D"));
var cursor = db.collection('inventory').find({ status: "D" });
$cursor = $db->inventory->find(['status' => 'D']);
$cursor = $db->coll("inventory")->find( { status => "D" } );
client[:inventory].find(status: 'D')
findObservable = collection.find(equal("status", "D"))
var filter = Builders<BsonDocument>.Filter.Eq("status", "D");
var result = collection.Find(filter).ToList();

Match an Embedded Document

Equality matches on the whole embedded document require an exact match of the specified <value> document, including the field order. For example, the following query selects all documents where the field size equals the document { h: 14, w: 21, uom: "cm" }:

db.inventory.find( { size: { h: 14, w: 21, uom: "cm" } } )
cursor = db.inventory.find(
    {"size": SON([("h", 14), ("w", 21), ("uom", "cm")])})
FindIterable<Document> findIterable = collection.find(eq("size", Document.parse("{ h: 14, w: 21, uom: 'cm' }")));
var cursor = db.collection('inventory').find({ 
  size: { h: 14, w: 21, uom: "cm" }
});
$cursor = $db->inventory->find(['size' => ['h' => 14, 'w' => 21, 'uom' => 'cm']]);
# Subdocument key order matters in this example so we have
# to use Tie::IxHash instead of a regular, unordered Perl hash.
$cursor = $db->coll("inventory")->find(
    { size => Tie::IxHash->new( h => 14, w => 21, uom => "cm" ) }
);
client[:inventory].find(size: { h: 14, w: 21, uom: 'cm' })
var findObservable = collection.find(equal("size", Document("h" -> 14, "w" -> 21, "uom" -> "cm")))
var filter = Builders<BsonDocument>.Filter.Eq("size", new BsonDocument { { "h", 14 }, { "w", 21 }, { "uom", "cm" } });
var result = collection.Find(filter).ToList();

Match a Field in an Embedded Document

The following example selects all documents where the field uom nested in the size field equals the string value "in":

db.inventory.find( { "size.uom": "in" } )
cursor = db.inventory.find({"size.uom": "in"})
findIterable = collection.find(eq("size.uom", "in"));
var cursor = db.collection('inventory').find({ 
  "size.uom": "in"
});
$cursor = $db->inventory->find(['size.uom' => 'in']);
$cursor = $db->coll("inventory")->find( { "size.uom" => "in" } );
client[:inventory].find('size.uom' => 'in')
findObservable = collection.find(equal("size.uom", "in"))
var filter = Builders<BsonDocument>.Filter.Eq("size.uom", "in");
var result = collection.Find(filter).ToList();

Match an Element in an Array

The following example queries for all documents where tags is an array that contains the string "red" as one of its elements:

db.inventory.find( { tags: "red" } )
cursor = db.inventory.find({"tags": "red"})
findIterable = collection.find(eq("tags", "red"));
var cursor = db.collection('inventory').find({ 
  tags: "red"
});
$cursor = $db->inventory->find(['tags' => 'red']);
$cursor = $db->coll("inventory")->find( { tags => "red" } );
client[:inventory].find(tags: 'red')
findObservable = collection.find(equal("tags", "red"))
var filter = Builders<BsonDocument>.Filter.Eq("tags", "red");
var result = collection.Find(filter).ToList();

Match an Array Exactly

The following example queries for all documents where the field tags value is an array with exactly two elements, "red" and "blank", in the specified order:

db.inventory.find( { tags: ["red", "blank"] } )
cursor = db.inventory.find({"tags": ["red", "blank"]})
FindIterable<Document> findIterable = collection.find(eq("tags", asList("red", "blank")));
var cursor = db.collection('inventory').find({ 
  tags: [ "red", "blank" ]
});
$cursor = $db->inventory->find(['tags' => ['red', 'blank']]);
$cursor = $db->coll("inventory")->find( { tags => [ "red", "blank" ] } );
client[:inventory].find(tags: ['red', 'blank'])
var findObservable = collection.find(equal("tags", Seq("red", "blank")))
var filter = Builders<BsonDocument>.Filter.Eq("tags", new[] { "red", "blank" });
var result = collection.Find(filter).ToList();

For more information and query examples, see Query Documents in the CRUD section.

To update or delete documents, see Update Documents and Delete Documents.

Next Steps

Once you complete the Getting Started Guide, you may find the following course and topics useful:

To learn more about the MongoDB query language and other MongoDB fundamentals, sign up for M001: MongoDB Basics.

Introduction Developers Administrators Reference

Introduction to MongoDB

Installation Guides

Databases and Collections

Documents

CRUD Operations

Aggregation

SQL to MongoDB

Indexes

Production Notes

Replica Sets

Sharded Clusters

MongoDB Security

Shell Methods

Query Operators

Reference

Glossary