Getting Started

The following page provides various examples for querying in theMongoDB shell. For examples using MongoDB drivers, refer to the linksin the Additional Examples section.

Examples

Click inside the shell to connect. Once connected, you can run theexamples in the shell above.

    1. Switch Database
    1. Populate a collection (Insert)
    1. Select All Documents
    1. Specify Equality Matches
    1. Specify Fields to Return (Projection)

Within the shell, db refers toyour current database. Type db to display the currentdatabase.

  1. db

The operation should return test, which is the defaultdatabase.

To switch databases, type use <db>. For example, to switchto the examples database:

  1. use examples

You do not need to create the database before you switch.MongoDB creates the database when you first store data in thatdatabase (such as create the first collection in the database).

To verify that your database is now examples, type db inthe shell above.

  1. db

To create a collection in the database, see the next tab.

MongoDB stores documents in collections. Collections are analogous totables in relational databases. If a collection does not exist,MongoDB creates the collection when you first store data for thatcollection.

The following example uses thedb.collection.insertMany() method to insert newdocuments into the inventorycollection. You can copy and paste the example into theshell above.

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

The operation returns a document that contains theacknowledgement indicator and an array that contains the_id of each successfully inserted documents.

To verify the insert, you can query the collection (See thenext tab).

To select the documents from a collection, you can use thedb.collection.find() method. To select all documentsin the collection, pass an empty document as the queryfilter document to the method.

In the shell, copy and paste thefollowing to return all documents in the inventorycollection.

  1. db.inventory.find({})

To format the results, append the .pretty() to thefind operation:

  1. db.inventory.find({}).pretty()

Note

The example assumes that you have populated theinventory collection from the previous step.

For an equality match (i.e. <field> equals <value>),specify <field>: <value> in the query filterdocument and pass to thedb.collection.find() method.

Note

The examples assumes that you have populated theinventory collection.

  • In the shell, copy and paste thefollowing to return documents where status field equals"D":
  1. db.inventory.find( { status: "D" } );
  • In the shell, copy and paste thefollowing to return document where qty field equals0:
  1. db.inventory.find( { qty: 0 } );
  • In the shell, copy and paste thefollowing to return document where qty field equals0 and status field equals "D":
  1. db.inventory.find( { qty: 0, status: "D" } );
  • In the shell, copy and paste thefollowing to return document where the uom field, nestedinside the size document, equals "in":
  1. db.inventory.find( { "size.uom": "in" } )
  • In the shell, copy and paste thefollowing to return document where the size field equalsthe document { h: 14, w: 21, uom: "cm" }:
  1. db.inventory.find( { size: { h: 14, w: 21, uom: "cm" } } )

Equality matches on the embedded document require an exactmatch, including the field order.

  • In the shell, copy and paste thefollowing to return documents where the tags arraycontains "red" as one of its elements:
  1. db.inventory.find( { tags: "red" } )

If the tags field is a string instead of an array, thenthe query is just an equality match.

  • In the shell, copy and paste thefollowing to return documents where the tags fieldmatches the specified array exactly, including the order:
  1. db.inventory.find( { tags: [ "red", "blank" ] } )

To specify fields to return, pass a projection document to thedb.collection.find(<query document>, <projectiondocument>) method. In the projectiondocument, specify:

  • <field>: 1 to include a field in the returned documents
  • <field>: 0 to exclude a field in the returned documents

In the shell, copy and paste thefollowing to return the _id, item, and the statusfields from all documents in the inventory collection:

  1. db.inventory.find( { }, { item: 1, status: 1 } );

You do not have to specify the _id field to return thefield. It returns by default. To exclude the field, set it to0 in the projection document. For example, copy and pastethe following to return only the item, and the statusfields in the matching documents:

  1. db.inventory.find( {}, { _id: 0, item: 1, status: 1 } );

Next Steps

Set up Your Own Deployment

To set up your own deployment:

MongoDB Atlas Free Tier ClusterMongoDB Atlas is a fast, easy, and free way to get started withMongoDB. To learn more, see theGetting Started with Atlas tutorial.
Local MongoDB installationFor more information on installing MongoDB locally, seeInstall MongoDB.

Additional Examples

For additional examples, including MongoDB driver specific examples(Python, Java, Node.js, etc.), see:

Query document examples- Query Documents- Query on Embedded/Nested Documents- Query an Array- Query an Array of Embedded Documents- Project Fields to Return from Query- Query for Null or Missing Fields
Update document examples- Update Documents
Delete document examples- Delete Documents

Additional Topics

IntroductionDevelopersAdministratorsReference
Introduction to MongoDBInstallation GuidesDatabases and CollectionsDocumentsCRUD OperationsAggregationSQL to MongoDBIndexesProduction NotesReplica SetsSharded ClustersMongoDB SecurityShell MethodsQuery OperatorsReferenceGlossary