Getting Started

Mongo Shell
Compass
Python
Node.js

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

本教程要求您连接到以下之一:

  • MongoDB Atlas Free Tier 集群 。 MongoDB Atlas 是一种快速,简单,免费的 MongoDB 入门方法。要了解更多信息,请参阅Atlas 入门教程。

  • 本地 MongoDB 安装 。有关在本地安装 MongoDB 的更多信息,请参阅Install MongoDB

Insert Documents

Mongo Shell
Compass
Python
Node.js

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.

  • Click Create Database.

Screeenshot after connecting with the "Create Database" button.

  • 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.

  • From the Collections tab, click the "inventory" collection link.

  • Click the Insert Document button.

Screeenshot of the collection with the "Insert Document" button.

  • 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.

  • 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.

有关更多信息和示例,请参见CRUD部分中的Insert Documents

Query Documents

选择所有文档

Mongo Shell
Compass
Python
Node.js
Java (Sync)
PHP
Motor
Java (Async)
C#
Perl
Ruby
Scala

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

db.inventory.find( {} )

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

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.
../../_images/compass-select-all.png
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.
Copy the following filter into the Compass query bar and click Find:

{ status: "D" }

../../_images/compass-find-filter-inventory.png

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

cursor = db.inventory.find({})

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" :

cursor = db.inventory.find({"status": "D"})

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

const cursor = db.collection('inventory').find({});

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" :

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

匹配嵌入式文档

整个嵌入式文档上的相等匹配要求与指定的<value>文档进行“精确”匹配,包括字段 Sequences。例如,以下查询选择字段size等于文档{ h: 14, w: 21, uom: "cm" }的所有文档:

Mongo Shell
Compass
Python
Java (Sync)
Node.js
PHP
Motor
Java (Async)
C#
Perl
Ruby
Scala
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

{ size: { h: 14, w: 21, uom: "cm" } }

Compass displaying documents with an exact match on an embedded document.

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' }")));
const 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字段中的字段uom等于字符串值"in"的所有文档:

Mongo Shell
Compass
Python
Java (Sync)
Node.js
PHP
Motor
Java (Async)
C#
Perl
Ruby
Scala
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

{ "size.uom": "in" }

Compass displaying documents with an exact match on a filter.

cursor = db.inventory.find({"size.uom": "in"})
findIterable = collection.find(eq("size.uom", "in"));
const 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"))

匹配数组中的元素

下面的示例查询所有文档,其中tags是包含字符串"red"作为其元素之一的数组:

Mongo Shell
Compass
Python
Java (Sync)
Node.js
PHP
Motor
Java (Async)
C#
Perl
Ruby
Scala
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

{ tags: "red" }

Compass displaying documents with arrays that contain the element from the filter.

cursor = db.inventory.find({"tags": "red"})
findIterable = collection.find(eq("tags", "red"));
const 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"))

精确匹配数组

下面的示例以指定 Sequences 查询字段tags的值是正好具有两个元素"red""blank"的数组的所有文档:

Mongo Shell
Compass
Python
Java (Sync)
Node.js
PHP
Motor
Java (Async)
C#
Perl
Ruby
Scala
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

{ tags: ["red", "blank"] }

Compass displaying documents with arrays that match the filter array exactly.

cursor = db.inventory.find({"tags": ["red", "blank"]})
FindIterable<Document> findIterable = collection.find(eq("tags", asList("red", "blank")));
const 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")))

有关更多信息和查询示例,请参见CRUD部分中的Query Documents

要更新或删除文档,请参阅Update DocumentsDelete Documents

Next Steps

完成入门指南后,您可能会发现以下类和主题很有用:

要了解有关 MongoDB 查询语言和其他 MongoDB 基础知识的更多信息,请注册M001:MongoDB 基础

IntroductionDevelopersAdministratorsReference
MongoDB 简介

Installation Guides
数据库和 collections
Documents
CRUD Operations
Aggregation
SQL 到 MongoDB
Indexes
Production Notes
Replica Sets
Sharded Clusters
MongoDB Security
Shell Methods
Query Operators
Reference
Glossary