Navigation

Getting Started

The following tutorial uses the mongo shell to insert data and perform query operations.

MongoDB Compass is the GUI for MongoDB. The following tutorial uses MongoDB Compass to connect to insert data and perform query operations.

The following tutorial uses the PyMongo Python driver to insert data and perform query operations.

The following tutorial uses the MongoDB Node.js Driver to insert data and perform query operations.

Prerequisites

This tutorial requires you to be connected to one of the following:

  • MongoDB Atlas Free Tier Cluster. MongoDB Atlas is a fast, easy, and free way to get started with MongoDB. Follow the Create an Atlas Free Tier Cluster tutorial to get started with MongoDB Atlas.
  • Local MongoDB installation. For more information on installing MongoDB locally, see Install MongoDB.

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.

  1. Click Create Database.

    Screeenshot after connecting with the "Create Database" button.
  2. Enter “retail” for the Database Name and “inventory” for the Collection Name then click Create Database. For more information, see Databases and Collections.

    Screeenshot of a entering the database and collection names.
  3. From the Collections tab, click the “inventory” collection link.

  4. Click the Insert Document button.

    Screeenshot of the collection with the "Insert Document" button.
  5. Insert the following document by entering the fields and values, then selecting the appropriate types from the dropdowns. Add fields by clicking the last line number, then clicking Add Field After ….

    { item: "journal", qty: 25, status: "A",
        size: { h: 14, w: 21, uom: "cm" }, tags: [ "blank", "red" ] }
    
    • For Object types, add nested fields by clicking the last field’s number and selecting Add Field After ….
    • For Array types, add additional elements to the array by clicking the last element’s line number and selecting Add Array Element After ….
    Adding a field and value to a document.
    Changing the type of a field-and-value pair.
  6. Repeat steps 4 and 5 to add additional documents:

    { 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" ] }
    

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:

Select the inventory collection from the Collections tab or the left-hand pane. By default, all documents are selected and additional documents are loaded by scrolling down.

To explicitly select all documents in the collection, pass an empty query filter document { } to the Filter input and click Find.

Compass displaying documents in a collection.

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( {} )
../../_images/compass-select-all.png
cursor = db.inventory.find({})
FindIterable<Document> findIterable = collection.find(new Document());
  var cursor = db.collection('inventory').find({});
$cursor = $db->inventory->find([]);
cursor = db.inventory.find({})
FindPublisher<Document> findPublisher = collection.find(new Document());
var filter = Builders<BsonDocument>.Filter.Empty;
var result = collection.Find(filter).ToList();
$cursor = $db->coll("inventory")->find( {} );
client[:inventory].find({})
var findObservable = collection.find(Document())

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 a query filter document to the Filter with the <field>: <value> of the desired documents. The following query filter document selects all documents where the status equals "D" from the inventory collection:

{ status: "D" }
Compass displaying documents that match a filter.

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" } )

Copy the following filter into the Compass query bar and click Find:

{ status: "D" }
../../_images/compass-find-filter-inventory.png
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.inventory.find({"status": "D"})
findPublisher = collection.find(eq("status", "D"));
var filter = Builders<BsonDocument>.Filter.Eq("status", "D");
var result = collection.Find(filter).ToList();
$cursor = $db->coll("inventory")->find( { status => "D" } );
client[:inventory].find(status: 'D')
findObservable = collection.find(equal("status", "D"))

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" } } )

Copy the following filter into the Compass query bar and click Find:

{ size: { h: 14, w: 21, uom: "cm" } }
../../_images/compass-match-embedded.png
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']]);
cursor = db.inventory.find(
    {"size": SON([("h", 14), ("w", 21), ("uom", "cm")])})
FindPublisher<Document> findPublisher = collection.find(eq("size", Document.parse("{ 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();
# 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")))
{ size: { h: 14, w: 21, uom: "cm" } }
Compass displaying documents with an exact match on an embedded document.

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" } )

Copy the following filter into the Compass query bar and click Find:

{ "size.uom": "in" }
../../_images/compass-find-nested-field.png
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.inventory.find({"size.uom": "in"})
findPublisher = collection.find(eq("size.uom", "in"));
var filter = Builders<BsonDocument>.Filter.Eq("size.uom", "in");
var result = collection.Find(filter).ToList();
$cursor = $db->coll("inventory")->find( { "size.uom" => "in" } );
client[:inventory].find('size.uom' => 'in')
findObservable = collection.find(equal("size.uom", "in"))
{ "size.uom": "in" }
Compass displaying documents with an exact match on a filter.

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" } )

Copy the following filter into the Compass query bar and click Find:

{ tags: "red" }
../../_images/compass-array-elem-match.png
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.inventory.find({"tags": "red"})
findPublisher = collection.find(eq("tags", "red"));
var filter = Builders<BsonDocument>.Filter.Eq("tags", "red");
var result = collection.Find(filter).ToList();
$cursor = $db->coll("inventory")->find( { tags => "red" } );
client[:inventory].find(tags: 'red')
findObservable = collection.find(equal("tags", "red"))
{ tags: "red" }
Compass displaying documents with arrays that contain the element from the filter.

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"] } )

Copy the following filter into the Compass query bar and click Find:

{ tags: ["red", "blank"] }
../../_images/compass-array-match-exact.png
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.inventory.find({"tags": ["red", "blank"]})
FindPublisher<Document> findPublisher = collection.find(eq("tags", asList("red", "blank")));
var filter = Builders<BsonDocument>.Filter.Eq("tags", new[] { "red", "blank" });
var result = collection.Find(filter).ToList();
$cursor = $db->coll("inventory")->find( { tags => [ "red", "blank" ] } );
client[:inventory].find(tags: ['red', 'blank'])
var findObservable = collection.find(equal("tags", Seq("red", "blank")))
{ tags: ["red", "blank"] }
Compass displaying documents with arrays that match the filter array exactly.

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