Getting Started起步

This tutorial walks you through inserting test data into a MongoDB database and querying that data using the documentation's embedded web shell. 本教程将指导您将测试数据插入MongoDB数据库,并使用文档的嵌入式web shell查询该数据。You do not need to deploy or install MongoDB to complete this tutorial.您无需部署或安装MongoDB即可完成本教程。

The examples in this tutorial use a subset of the Sample Mflix Dataset, which is part of the sample data included in MongoDB's cloud-hosted service, MongoDB Atlas. 本教程中的示例使用示例Mflix数据集的子集,该数据集是MongoDB云托管服务MongoDB Atlas中包含的示例数据的一部分。Atlas requires no installation overhead and offers a free tier to get started. Atlas不需要安装开销,并且提供了一个免费的开始层。After completing this tutorial, you can use Atlas to explore additional sample data or host your own data.完成本教程后,您可以使用Atlas来探索其他示例数据或托管自己的数据。

Click inside the shell to connect. 在shell内部单击以连接。Once connected, you can run the examples in the shell above.连接后,可以运行上面shell中的示例。

Switch Database

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

db

The operation should return test, which is the default database.

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

use examples

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

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

db

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

Populate a Collection (Insert)

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

The following example uses the db.collection.insertMany() method to insert new documents into the movies collection. You can copy and paste the example into the shell above.

db.movies.insertMany([
   {
      title: 'Titanic',
      year: 1997,
      genres: [ 'Drama', 'Romance' ],
      rated: 'PG-13',
      languages: [ 'English', 'French', 'German', 'Swedish', 'Italian', 'Russian' ],
      released: ISODate("1997-12-19T00:00:00.000Z"),
      awards: {
         wins: 127,
         nominations: 63,
         text: 'Won 11 Oscars. Another 116 wins & 63 nominations.'
      },
      cast: [ 'Leonardo DiCaprio', 'Kate Winslet', 'Billy Zane', 'Kathy Bates' ],
      directors: [ 'James Cameron' ]
   },
   {
      title: 'The Dark Knight',
      year: 2008,
      genres: [ 'Action', 'Crime', 'Drama' ],
      rated: 'PG-13',
      languages: [ 'English', 'Mandarin' ],
      released: ISODate("2008-07-18T00:00:00.000Z"),
      awards: {
         wins: 144,
         nominations: 106,
         text: 'Won 2 Oscars. Another 142 wins & 106 nominations.'
      },
      cast: [ 'Christian Bale', 'Heath Ledger', 'Aaron Eckhart', 'Michael Caine' ],
      directors: [ 'Christopher Nolan' ]
   },
   {
      title: 'Spirited Away',
      year: 2001,
      genres: [ 'Animation', 'Adventure', 'Family' ],
      rated: 'PG',
      languages: [ 'Japanese' ],
      released: ISODate("2003-03-28T00:00:00.000Z"),
      awards: {
         wins: 52,
         nominations: 22,
         text: 'Won 1 Oscar. Another 51 wins & 22 nominations.'
      },
      cast: [ 'Rumi Hiiragi', 'Miyu Irino', 'Mari Natsuki', 'Takashi Naitè' ],
      directors: [ 'Hayao Miyazaki' ]
   },
   {
      title: 'Casablanca',
      genres: [ 'Drama', 'Romance', 'War' ],
      rated: 'PG',
      cast: [ 'Humphrey Bogart', 'Ingrid Bergman', 'Paul Henreid', 'Claude Rains' ],
      languages: [ 'English', 'French', 'German', 'Italian' ],
      released: ISODate("1943-01-23T00:00:00.000Z"),
      directors: [ 'Michael Curtiz' ],
      awards: {
         wins: 9,
         nominations: 6,
         text: 'Won 3 Oscars. Another 6 wins & 6 nominations.'
      },
      lastupdated: '2015-09-04 00:22:54.600000000',
      year: 1942
   }
])

The operation returns a document that contains the acknowledgement indicator and an array that contains the _id of each successfully inserted documents.

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

Select All Documents

To select the documents from a collection, you can use the db.collection.find() method. To select all documents in the collection, pass an empty document as the query filter document to the method.

In the shell, copy and paste the following to return all documents in the movies collection.

db.movies.find( { } )

Filter Data with Comparison Operators

For an equality match (<field> equals <value>), specify <field>: <value> in the query filter document and pass to the db.collection.find() method.

  • In the shell, run the following query to find movies that were directed by Christopher Nolan:

    db.movies.find( { "directors": "Christopher Nolan" } );

You can use comparison operators to perform more advanced queries:

  • Run the following query to return movies that were released before the year 2000:

    db.movies.find( { "released": { $lt: ISODate("2000-01-01") } } );
  • Run the following query to return movies that won more than 100 awards:

    db.movies.find( { "awards.wins": { $gt: 100 } } );
  • Run the following query to return movies where the languages array contains either Japanese or Mandarin:

    db.movies.find( { "languages": { $in: [ "Japanese", "Mandarin" ] } } )

Specify Fields to Return (Projection)

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

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

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

In the shell, run the following query to return the id, title, directors, and year fields from all documents in the movies collection:

db.movies.find( { }, { "title": 1, "directors": 1, "year": 1 } );

You do not have to specify the _id field to return the field. It returns by default. To exclude the field, set it to 0 in the projection document. For example, run the following query to return only the title, and the genres fields in the matching documents:

db.movies.find( { }, { "_id": 0, "title": 1, "genres": 1 } );

Aggregate Data ($group)

You can use aggregation to group values from multiple documents together and return a single result. Aggregation in MongoDB is performed with an aggregation pipeline.

While find() operations are useful for data retrieval, the aggregation pipeline allows you to manipulate data, perform calculations, and write more expressive queries than simple CRUD operations.

In the shell, run the following aggregation pipeline to count the number of occurrences of each genre value:

db.movies.aggregate( [
   { $unwind: "$genres" },
   {
     $group: {
       _id: "$genres",
       genreCount: { $count: { } }
     }
   },
   { $sort: { "genreCount": -1 } }
] )

The pipeline uses:

  • $unwind to output a document for each element in the genres array.

  • $group and the $count accumulator to count the number of occurrences of each genre. This value is stored in the genreCount field.

  • $sort to sort the resulting documents by the genreCount field in descending order.

Next Steps下一步

Set up Your Own Deployment设置自己的部署

To set up your own deployment:要设置自己的部署,请执行以下操作:

DeploymentDescription描述
MongoDB Atlas Free Tier ClusterMongoDB Atlas自由层集群MongoDB Atlas is a fast, easy, and free way to get started with MongoDB. MongoDB Atlas是一种快速、简单、免费的MongoDB入门方式。To learn more, see the Getting Started with Atlas tutorial.要了解更多信息,请参阅Atlas入门教程。
Local MongoDB installation本地MongoDB安装For more information on installing MongoDB locally, see Install MongoDB.有关在本地安装MongoDB的更多信息,请参阅安装MongoDB

Additional Examples更多示例

For additional examples, including MongoDB driver specific examples (Python, Java, Node.js, etc.), see:有关其他示例,包括特定于MongoDB驱动程序的示例(Python、Java、Node.js等),请参阅:

Query document examples查询文档示例
Update document examples更新文档示例
Delete document examples删除文档示例

Additional Topics附加主题

Introduction介绍Developers开发者Administrators管理员Reference参考

Introduction to MongoDBMongoDB简介

Installation Guides安装指南

Databases and Collections数据库和集合

Documents文件

CRUD OperationsCRUD操作

Aggregation聚合

SQL to MongoDB

Indexes索引

Production Notes制作说明

Replica Sets副本集

Sharded Clusters分片群集

MongoDB SecurityMongoDB安全

Shell Methods方法

Query Operators查询运算符

Reference参考

Glossary术语汇编

←  Introduction to MongoDBDatabases and Collections →