Query Documents查询文档

This page provides examples in:本页提供了以下示例:

This page provides examples of query operations using the db.collection.find() method in the mongo shell. 此页面提供了使用mongo shell中的db.collection.find()方法进行查询操作的示例。The examples on this page use the inventory collection. 本页上的示例使用inventory集合。To populate the inventory collection, run the following:要填充inventory集合,请运行以下操作:

This page provides examples of query operations using MongoDB Compass. 本页提供使用MongoDB Compass的查询操作示例。The examples on this page use the inventory collection. 本页上的示例使用inventory集合。Populate the inventory collection with the following documents:使用以下文档填充inventory集合:

This page provides examples of query operations using the pymongo.collection.Collection.find() method in the PyMongo Python driver. The examples on this page use the inventory collection. 本页上的示例使用inventory集合。To populate the inventory collection, run the following:要填充inventory集合,请运行以下操作:

This page provides examples of query operations using the com.mongodb.client.MongoCollection.find method in the MongoDB Java Synchronous Driver.本页提供了使用mongodb Java同步驱动程序中的com.mongodb.client.MongoCollection.find方法进行查询操作的示例。

Tip

The driver provides com.mongodb.client.model.Filters helper methods to facilitate the creation of filter documents. 驱动程序提供com.mongodb.client.model.Filters帮助程序方法,以方便创建筛选文档。The examples on this page use these methods to create the filter documents.本页上的示例使用这些方法创建筛选文档。

The examples on this page use the inventory collection. 本页上的示例使用inventory集合。To populate the inventory collection, run the following:要填充inventory集合,请运行以下操作:

This page provides examples of query operations using the Collection.find() method in the MongoDB Node.js Driver. 此页面提供了使用MongoDB Node.js驱动程序中的Collection.find()方法进行查询操作的示例。The examples on this page use the inventory collection. 本页上的示例使用inventory集合。To populate the inventory collection, run the following:要填充inventory集合,请运行以下操作:

This page provides examples of query operations using the MongoDB\Collection::find() method in the MongoDB PHP Library. The examples on this page use the inventory collection. 本页上的示例使用inventory集合。To populate the inventory collection, run the following:要填充inventory集合,请运行以下操作:

This page provides examples of query operations using the motor.motor_asyncio.AsyncIOMotorCollection.find() method in the Motor driver. The examples on this page use the inventory collection. 本页上的示例使用inventory集合。To populate the inventory collection, run the following:要填充inventory集合,请运行以下操作:

This page provides examples of query operations using the com.mongodb.reactivestreams.client.MongoCollection.find method in the MongoDB Java Reactive Streams Driver.

The examples on this page use the inventory collection. 本页上的示例使用inventory集合。To populate the inventory collection, run the following:要填充inventory集合,请运行以下操作:

This page provides examples of query operations using the MongoCollection.Find() method in the MongoDB C# Driver. The examples on this page use the inventory collection. 本页上的示例使用inventory集合。To populate the inventory collection, run the following:要填充inventory集合,请运行以下操作:

This page provides examples of query operations using the MongoDB::Collection::find() method in the MongoDB Perl Driver. The examples on this page use the inventory collection. 本页上的示例使用inventory集合。To populate the inventory collection, run the following:要填充inventory集合,请运行以下操作:

This page provides examples of query operations using the Mongo::Collection#find() method in the MongoDB Ruby Driver. The examples on this page use the inventory collection. 本页上的示例使用inventory集合。To populate the inventory collection, run the following:要填充inventory集合,请运行以下操作:

This page provides examples of query operations using the collection.find() method in the MongoDB Scala Driver. The examples on this page use the inventory collection. 本页上的示例使用inventory集合。To populate the inventory collection, run the following:要填充inventory集合,请运行以下操作:

This page provides examples of query operations using the Collection.Find function in the MongoDB Go Driver. The examples on this page use the inventory collection. 本页上的示例使用inventory集合。To populate the inventory collection, run the following:要填充inventory集合,请运行以下操作:

db.inventory.insertMany([
   { item: "journal", qty: 25, size: { h: 14, w: 21, uom: "cm" }, status: "A" },
   { item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in" }, status: "A" },
   { item: "paper", qty: 100, size: { h: 8.5, w: 11, uom: "in" }, status: "D" },
   { item: "planner", qty: 75, size: { h: 22.85, w: 30, uom: "cm" }, status: "D" },
   { item: "postcard", qty: 45, size: { h: 10, w: 15.25, uom: "cm" }, status: "A" }
]);

You can run the operation in the web shell below:您可以在下面的web shell中运行该操作:

[
   { item: "journal", qty: 25, size: { h: 14, w: 21, uom: "cm" }, status: "A" },
   { item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in" }, status: "A" },
   { item: "paper", qty: 100, size: { h: 8.5, w: 11, uom: "in" }, status: "D" },
   { item: "planner", qty: 75, size: { h: 22.85, w: 30, uom: "cm" }, status: "D" },
   { item: "postcard", qty: 45, size: { h: 10, w: 15.25, uom: "cm" }, status: "A" }
]

For instructions on inserting documents in MongoDB Compass, see Insert Documents.

db.inventory.insert_many([
    {"item": "journal",
     "qty": 25,
     "size": {"h": 14, "w": 21, "uom": "cm"},
     "status": "A"},
    {"item": "notebook",
     "qty": 50,
     "size": {"h": 8.5, "w": 11, "uom": "in"},
     "status": "A"},
    {"item": "paper",
     "qty": 100,
     "size": {"h": 8.5, "w": 11, "uom": "in"},
     "status": "D"},
    {"item": "planner",
     "qty": 75, "size": {"h": 22.85, "w": 30, "uom": "cm"},
     "status": "D"},
    {"item": "postcard",
     "qty": 45,
     "size": {"h": 10, "w": 15.25, "uom": "cm"},
     "status": "A"}])
collection.insertMany(asList(
        Document.parse("{ item: 'journal', qty: 25, size: { h: 14, w: 21, uom: 'cm' }, status: 'A' }"),
        Document.parse("{ item: 'notebook', qty: 50, size: { h: 8.5, w: 11, uom: 'in' }, status: 'A' }"),
        Document.parse("{ item: 'paper', qty: 100, size: { h: 8.5, w: 11, uom: 'in' }, status: 'D' }"),
        Document.parse("{ item: 'planner', qty: 75, size: { h: 22.85, w: 30, uom: 'cm' }, status: 'D' }"),
        Document.parse("{ item: 'postcard', qty: 45, size: { h: 10, w: 15.25, uom: 'cm' }, status: 'A' }")
));
await db.collection('inventory').insertMany([
  {
    item: 'journal',
    qty: 25,
    size: { h: 14, w: 21, uom: 'cm' },
    status: 'A'
  },
  {
    item: 'notebook',
    qty: 50,
    size: { h: 8.5, w: 11, uom: 'in' },
    status: 'A'
  },
  {
    item: 'paper',
    qty: 100,
    size: { h: 8.5, w: 11, uom: 'in' },
    status: 'D'
  },
  {
    item: 'planner',
    qty: 75,
    size: { h: 22.85, w: 30, uom: 'cm' },
    status: 'D'
  },
  {
    item: 'postcard',
    qty: 45,
    size: { h: 10, w: 15.25, uom: 'cm' },
    status: 'A'
  }
]);
$insertManyResult = $db->inventory->insertMany([
    [
        'item' => 'journal',
        'qty' => 25,
        'size' => ['h' => 14, 'w' => 21, 'uom' => 'cm'],
        'status' => 'A',
    ],
    [
        'item' => 'notebook',
        'qty' => 50,
        'size' => ['h' => 8.5, 'w' => 11, 'uom' => 'in'],
        'status' => 'A',
    ],
    [
        'item' => 'paper',
        'qty' => 100,
        'size' => ['h' => 8.5, 'w' => 11, 'uom' => 'in'],
        'status' => 'D',
    ],
    [
        'item' => 'planner',
        'qty' => 75,
        'size' => ['h' => 22.85, 'w' => 30, 'uom' => 'cm'],
        'status' => 'D',
    ],
    [
        'item' => 'postcard',
        'qty' => 45,
        'size' => ['h' => 10, 'w' => 15.25, 'uom' => 'cm'],
        'status' => 'A',
    ],
]);
await db.inventory.insert_many([
    {"item": "journal",
     "qty": 25,
     "size": {"h": 14, "w": 21, "uom": "cm"},
     "status": "A"},
    {"item": "notebook",
     "qty": 50,
     "size": {"h": 8.5, "w": 11, "uom": "in"},
     "status": "A"},
    {"item": "paper",
     "qty": 100,
     "size": {"h": 8.5, "w": 11, "uom": "in"},
     "status": "D"},
    {"item": "planner",
     "qty": 75, "size": {"h": 22.85, "w": 30, "uom": "cm"},
     "status": "D"},
    {"item": "postcard",
     "qty": 45,
     "size": {"h": 10, "w": 15.25, "uom": "cm"},
     "status": "A"}])
Publisher<Success> insertManyPublisher = collection.insertMany(asList(
        Document.parse("{ item: 'journal', qty: 25, size: { h: 14, w: 21, uom: 'cm' }, status: 'A' }"),
        Document.parse("{ item: 'notebook', qty: 50, size: { h: 8.5, w: 11, uom: 'in' }, status: 'A' }"),
        Document.parse("{ item: 'paper', qty: 100, size: { h: 8.5, w: 11, uom: 'in' }, status: 'D' }"),
        Document.parse("{ item: 'planner', qty: 75, size: { h: 22.85, w: 30, uom: 'cm' }, status: 'D' }"),
        Document.parse("{ item: 'postcard', qty: 45, size: { h: 10, w: 15.25, uom: 'cm' }, status: 'A' }")
));
var documents = new BsonDocument[]
{
    new BsonDocument
    {
        { "item", "journal" },
        { "qty", 25 },
        { "size", new BsonDocument { { "h", 14 }, { "w", 21 }, {  "uom", "cm"} } },
        { "status", "A" }
    },
    new BsonDocument
    {
        { "item", "notebook" },
        { "qty", 50 },
        { "size", new BsonDocument { { "h",  8.5 }, { "w", 11 }, {  "uom", "in"} } },
        { "status", "A" }
    },
    new BsonDocument
    {
        { "item", "paper" },
        { "qty", 100 },
        { "size", new BsonDocument { { "h",  8.5 }, { "w", 11 }, {  "uom", "in"} } },
        { "status", "D" }
    },
    new BsonDocument
    {
        { "item", "planner" },
        { "qty", 75 },
        { "size", new BsonDocument { { "h", 22.85 }, { "w", 30  }, {  "uom", "cm"} } },
        { "status", "D" }
    },
    new BsonDocument
    {
        { "item", "postcard" },
        { "qty", 45 },
        { "size", new BsonDocument { { "h", 10 }, { "w", 15.25 }, {  "uom", "cm"} } },
        { "status", "A" }
    },
};
collection.InsertMany(documents);
$db->coll("inventory")->insert_many(
    [
        {
            item   => "journal",
            qty    => 25,
            size   => { h => 14, w => 21, uom => "cm" },
            status => "A"
        },
        {
            item   => "notebook",
            qty    => 50,
            size   => { h => 8.5, w => 11, uom => "in" },
            status => "A"
        },
        {
            item   => "paper",
            qty    => 100,
            size   => { h => 8.5, w => 11, uom => "in" },
            status => "D"
        },
        {
            item   => "planner",
            qty    => 75,
            size   => { h => 22.85, w => 30, uom => "cm" },
            status => "D"
        },
        {
            item   => "postcard",
            qty    => 45,
            size   => { h => 10, w => 15.25, uom => "cm" },
            status => "A"
        }
    ]
);
client[:inventory].insert_many([{ item: 'journal',
                                  qty: 25,
                                  size: { h: 14, w: 21, uom: 'cm' },
                                  status: 'A' },
                                { item: 'notebook',
                                  qty: 50,
                                  size: { h: 8.5, w: 11, uom: 'in' },
                                  status: 'A' },
                                { item: 'paper',
                                  qty: 100,
                                  size: { h: 8.5, w: 11, uom: 'in' },
                                  status: 'D' },
                                { item: 'planner',
                                  qty: 75,
                                  size: { h: 22.85, w: 30, uom: 'cm' },
                                  status: 'D' },
                                { item: 'postcard',
                                  qty: 45,
                                  size: { h: 10, w: 15.25, uom: 'cm' },
                                  status: 'A' }
                               ])
collection.insertMany(Seq(
  Document("""{ item: "journal", qty: 25, size: { h: 14, w: 21, uom: "cm" }, status: "A" }"""),
  Document("""{ item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in" }, status: "A" }"""),
  Document("""{ item: "paper", qty: 100, size: { h: 8.5, w: 11, uom: "in" }, status: "D" }"""),
  Document("""{ item: "planner", qty: 75, size: { h: 22.85, w: 30, uom: "cm" }, status: "D" }"""),
  Document("""{ item: "postcard", qty: 45, size: { h: 10, w: 15.25, uom: "cm" }, status: "A" }""")
)).execute()
docs := []interface{}{
	bson.D{
		{"item", "journal"},
		{"qty", 25},
		{"size", bson.D{
			{"h", 14},
			{"w", 21},
			{"uom", "cm"},
		}},
		{"status", "A"},
	},
	bson.D{
		{"item", "notebook"},
		{"qty", 50},
		{"size", bson.D{
			{"h", 8.5},
			{"w", 11},
			{"uom", "in"},
		}},
		{"status", "A"},
	},
	bson.D{
		{"item", "paper"},
		{"qty", 100},
		{"size", bson.D{
			{"h", 8.5},
			{"w", 11},
			{"uom", "in"},
		}},
		{"status", "D"},
	},
	bson.D{
		{"item", "planner"},
		{"qty", 75},
		{"size", bson.D{
			{"h", 22.85},
			{"w", 30},
			{"uom", "cm"},
		}},
		{"status", "D"},
	},
	bson.D{
		{"item", "postcard"},
		{"qty", 45},
		{"size", bson.D{
			{"h", 10},
			{"w", 15.25},
			{"uom", "cm"},
		}},
		{"status", "A"},
	},
}

result, err := coll.InsertMany(context.Background(), docs)

Select All Documents in a Collection选择集合中的所有文档

To select all documents in the collection, pass an empty document as the query filter parameter to the find method. 要选择集合中的所有文档,请将空文档作为查询筛选器参数传递给find方法。The query filter parameter determines the select criteria:查询过滤器参数确定选择条件:

To select all documents in the collection, pass an empty document as the query filter parameter to the query bar. 要选择集合中的所有文档,请将空文档作为查询筛选参数传递给查询栏The query filter parameter determines the select criteria:查询过滤器参数确定选择条件:

To select all documents in the collection, pass an empty document as the query filter parameter to the find method. 要选择集合中的所有文档,请将空文档作为查询筛选器参数传递给find方法。The query filter parameter determines the select criteria:查询过滤器参数确定选择条件:

To select all documents in the collection, pass an empty document as the query filter parameter to the find method. 要选择集合中的所有文档,请将空文档作为查询筛选器参数传递给find方法。The query filter parameter determines the select criteria:查询过滤器参数确定选择条件:

To select all documents in the collection, pass an empty document as the query filter parameter to the find method. 要选择集合中的所有文档,请将空文档作为查询筛选器参数传递给find方法。The query filter parameter determines the select criteria:查询过滤器参数确定选择条件:

To select all documents in the collection, pass an empty document as the query filter parameter to the find method. The query filter parameter determines the select criteria:

To select all documents in the collection, pass an empty document as the query filter parameter to the find method. The query filter parameter determines the select criteria:

To select all documents in the collection, pass an empty document as the query filter parameter to the find method. The query filter parameter determines the select criteria:

To select all documents in the collection, pass an empty document as the query filter parameter to the find method. The query filter parameter determines the select criteria:

To select all documents in the collection, pass an empty document as the query filter parameter to the find method. The query filter parameter determines the select criteria:

To select all documents in the collection, pass an empty document as the query filter parameter to the find method. The query filter parameter determines the select criteria:

To select all documents in the collection, pass an empty document as the query filter parameter to the find method. The query filter parameter determines the select criteria:

To select all documents in the collection, pass an empty document as the query filter parameter to the find method. The query filter parameter determines the select criteria:

db.inventory.find( {} )
../../_images/compass-select-all.png
cursor = db.inventory.find({})
FindIterable<Document> findIterable = collection.find(new Document());
const 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())
cursor, err := coll.Find(
	context.Background(),
	bson.D{},
)

This operation corresponds to the following SQL statement:此操作对应于以下SQL语句:

SELECT * FROM inventory

For more information on the syntax of the method, see find().有关该方法语法的详细信息,请参阅find()

For more information on the MongoDB Compass query bar, see Query Bar.有关MongoDB Compass查询栏的更多信息,请参阅查询栏

For more information on the syntax of the method, see find().

For more information on the syntax of the method, see com.mongodb.client.MongoCollection.find.有关该方法语法的更多信息,请参阅com.mongodb.client.MongoCollection.find

For more information on the syntax of the method, see find().有关该方法语法的详细信息,请参阅find()

For more information on the syntax of the method, see find().有关该方法语法的详细信息,请参阅find()

For more information on the syntax of the method, see com.mongodb.reactivestreams.client.MongoCollection.find.有关该方法语法的更多信息,请参阅com.mongodb.reactivestreams.client.MongoCollection.find

For more information on the syntax of the method, see Find().

For more information on the syntax of the method, see find().

For more information on the syntax of the method, see find().

For more information on the syntax of the method, see collection.find().

Specify Equality Condition指定相等条件

To specify equality conditions, use <field>:<value> expressions in the query filter document:要指定相等条件,请使用查询筛选文档中的<field>:<value>表达式:

{ <field1>: <value1>, ... }

To specify equality conditions, use <field>:<value> expressions in the query filter document:要指定相等条件,请使用查询筛选文档中的<field>:<value>表达式:

{ <field1>: <value1>, ... }

To specify equality conditions, use <field>:<value> expressions in the query filter document:要指定相等条件,请使用查询筛选文档中的<field>:<value>表达式:

{ <field1>: <value1>, ... }

To specify equality conditions, use the com.mongodb.client.model.Filters.eq_ method to create the query filter document:要指定相等条件,请使用com.mongodb.client.model.Filters.eq_方法创建查询筛选器文档

and(eq( <field1>, <value1>), eq( <field2>, <value2>) ...)

To specify equality conditions, use <field>:<value> expressions in the query filter document:要指定相等条件,请使用查询筛选文档中的<field>:<value>表达式:

{ <field1>: <value1>, ... }

To specify equality conditions, use <field> => <value> expressions in the query filter document:要指定相等条件,请使用查询筛选文档中的<field> => <value>表达式:

[ <field1> => <value1>, ... ]

To specify equality conditions, use <field>:<value> expressions in the query filter document:要指定相等条件,请使用查询筛选文档中的<field>:<value>表达式:

{ <field1>: <value1>, ... }

To specify equality conditions, use the com.mongodb.client.model.Filters.eq method to create the query filter document:要指定相等条件,请使用com.mongodb.client.model.Filters.eq方法创建查询筛选文档

and(eq( <field1>, <value1>), eq( <field2>, <value2>) ...)

To specify equality conditions, construct a filter using the Eq method:

Builders<BsonDocument>.Filter.Eq(<field>, <value>);

To specify equality conditions, use <field> => <value> expressions in the query filter document:

{ <field1> => <value1>, ... }

To specify equality conditions, use <field> => <value> expressions in the query filter document:

{ <field1> => <value1>, ... }

To specify equality conditions, use the com.mongodb.client.model.Filters.eq_ method to create the query filter document:

and(equal(<field1>, <value1>), equal(<field2>, <value2>) ...)

The following example selects from the inventory collection all documents where the status equals "D":以下示例从inventory集合中选择status"D"的所有文档:

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

Copy the following filter into the Compass query bar and click Find:将以下过滤器复制到Compass查询栏中,然后单击“查找”:

{ status: "D" }
../../_images/compass-find-filter-inventory.png
cursor = db.inventory.find({"status": "D"})
findIterable = collection.find(eq("status", "D"));
const 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"))
cursor, err := coll.Find(
	context.Background(),
	bson.D{{"status", "D"}},
)

This operation corresponds to the following SQL statement:此操作对应于以下SQL语句:

SELECT * FROM inventory WHERE status = "D"

Note

The MongoDB Compass query bar autocompletes the current query based on the keys in your collection’s documents, including keys in embedded sub-documents.MongoDB Compass查询栏根据集合文档中的键(包括嵌入子文档中的键)自动完成当前查询。

Specify Conditions Using Query Operators使用查询运算符指定条件

A query filter document can use the query operators to specify conditions in the following form:查询筛选文档可以使用查询运算符以以下形式指定条件:

{ <field1>: { <operator1>: <value1> }, ... }

A query filter document can use the query operators to specify conditions in the following form:查询筛选文档可以使用查询运算符以以下形式指定条件:

{ <field1>: { <operator1>: <value1> }, ... }

A query filter document can use the query operators to specify conditions in the following form:

{ <field1>: { <operator1>: <value1> }, ... }

In addition to the equality condition, MongoDB provides various query operators to specify filter conditions. 除了相等条件外,MongoDB还提供了各种查询运算符来指定过滤条件。Use the com.mongodb.client.model.Filters helper methods to facilitate the creation of filter documents. 使用com.mongodb.client.model.Filters助手方法来帮助创建筛选文档。For example:例如:

and(gte(<field1>, <value1>), lt(<field2>, <value2>), eq(<field3>, <value3>))

A query filter document can use the query operators to specify conditions in the following form:查询筛选文档可以使用查询运算符以以下形式指定条件:

{ <field1>: { <operator1>: <value1> }, ... }

A query filter document can use the query operators to specify conditions in the following form:

[ <field1> => [ <operator1> => <value1> ], ... ]

A query filter document can use the query operators to specify conditions in the following form:

{ <field1>: { <operator1>: <value1> }, ... }

In addition to the equality condition, MongoDB provides various query operators to specify filter conditions. Use the com.mongodb.client.model.Filters helper methods to facilitate the creation of filter documents. For example:例如:

and(gte(<field1>, <value1>), lt(<field2>, <value2>), eq(<field3>, <value3>))

In addition to the equality filter, MongoDB provides various query operators to specify filter conditions. Use the FilterDefinitionBuilder methods to create a filter document. For example:例如:

var builder = Builders<BsonDocument>.Filter;
builder.And(builder.Eq(<field1>, <value1>), builder.Lt(<field2>, <value2>));

A query filter document can use the query operators to specify conditions in the following form:

{ <field1> => { <operator1> => <value1> }, ... }

A query filter document can use the query operators to specify conditions in the following form:

{ <field1> => { <operator1> => <value1> }, ... }

In addition to the equality condition, MongoDB provides various query operators to specify filter conditions. Use the com.mongodb.client.model.Filters_ helper methods to facilitate the creation of filter documents. For example:例如:

and(gte(<field1>, <value1>), lt(<field2>, <value2>), equal(<field3>, <value3>))

The following example retrieves all documents from the inventory collection where status equals either "A" or "D":以下示例从inventory集合中检索status"A""D"的所有文档:

db.inventory.find( { status: { $in: [ "A", "D" ] } } )

Copy the following filter into the Compass query bar and click Find:将以下过滤器复制到Compass查询栏中,然后单击“查找”:

{ status: { $in: [ "A", "D" ] } }
../../_images/compass-find-filter-query-op.png
cursor = db.inventory.find({"status": {"$in": ["A", "D"]}})
findIterable = collection.find(in("status", "A", "D"));
const cursor = db.collection('inventory').find({
  status: { $in: ['A', 'D'] }
});
$cursor = $db->inventory->find(['status' => ['$in' => ['A', 'D']]]);
cursor = db.inventory.find({"status": {"$in": ["A", "D"]}})
findPublisher = collection.find(in("status", "A", "D"));
var filter = Builders<BsonDocument>.Filter.In("status", new[] { "A", "D" });
var result = collection.Find(filter).ToList();
$cursor = $db->coll("inventory")->find( { status => { '$in' => [ "A", "D" ] } } );
client[:inventory].find(status: { '$in' => [ 'A', 'D' ]})
findObservable = collection.find(in("status", "A", "D"))
cursor, err := coll.Find(
	context.Background(),
	bson.D{{"status", bson.D{{"$in", bson.A{"A", "D"}}}}})

Note

Although you can express this query using the $or operator, use the $in operator rather than the $or operator when performing equality checks on the same field.尽管可以使用$or运算符表示此查询,但在对同一字段执行相等性检查时,请使用$in运算符而不是$or运算符。

The operation corresponds to the following SQL statement:该操作对应于以下SQL语句:

SELECT * FROM inventory WHERE status in ("A", "D")

Refer to the Query and Projection Operators document for the complete list of MongoDB query operators.有关MongoDB查询运算符的完整列表,请参阅查询和投影运算符文档。

Specify AND Conditions规定AND条件

A compound query can specify conditions for more than one field in the collection’s documents. 复合查询可以为集合文档中的多个字段指定条件。Implicitly, a logical AND conjunction connects the clauses of a compound query so that the query selects the documents in the collection that match all the conditions.逻辑AND连词隐式地连接复合查询的子句,以便查询选择集合中匹配所有条件的文档。

The following example retrieves all documents in the inventory collection where the status equals "A" and qty is less than ($lt) 30:以下示例检索inventory集合中status"A"qty小于($lt30的所有文档:

db.inventory.find( { status: "A", qty: { $lt: 30 } } )

Copy the following filter into the Compass query bar and click Find:将以下过滤器复制到Compass查询栏中,然后单击“查找”:

{ status: "A", qty: { $lt: 30 } }
../../_images/compass-find-filter-and.png
cursor = db.inventory.find({"status": "A", "qty": {"$lt": 30}})
findIterable = collection.find(and(eq("status", "A"), lt("qty", 30)));
const cursor = db.collection('inventory').find({
  status: 'A',
  qty: { $lt: 30 }
});
$cursor = $db->inventory->find([
    'status' => 'A',
    'qty' => ['$lt' => 30],
]);
cursor = db.inventory.find({"status": "A", "qty": {"$lt": 30}})
findPublisher = collection.find(and(eq("status", "A"), lt("qty", 30)));
var builder = Builders<BsonDocument>.Filter;
var filter = builder.And(builder.Eq("status", "A"), builder.Lt("qty", 30));
var result = collection.Find(filter).ToList();
$cursor = $db->coll("inventory")->find( { status => "A", qty => { '$lt' => 30 } } );
client[:inventory].find(status: 'A', qty: { '$lt' => 30 })
findObservable = collection.find(and(equal("status", "A"), lt("qty", 30)))
cursor, err := coll.Find(
	context.Background(),
	bson.D{
		{"status", "A"},
		{"qty", bson.D{{"$lt", 30}}},
	})

The operation corresponds to the following SQL statement:该操作对应于以下SQL语句:

SELECT * FROM inventory WHERE status = "A" AND qty < 30

See comparison operators for other MongoDB comparison operators.有关其他MongoDB比较运算符,请参阅比较运算符

Specify OR Conditions规定OR条件

Using the $or operator, you can specify a compound query that joins each clause with a logical OR conjunction so that the query selects the documents in the collection that match at least one condition.使用$or运算符,可以指定一个复合查询,将每个子句与逻辑OR连接起来,以便查询选择集合中至少符合一个条件的文档。

The following example retrieves all documents in the collection where the status equals "A" or qty is less than ($lt) 30:以下示例检索集合中status等于"A"qty小于($lt30的所有文档:

db.inventory.find( { $or: [ { status: "A" }, { qty: { $lt: 30 } } ] } )

Copy the following filter into the Compass query bar and click Find:将以下过滤器复制到Compass查询栏中,然后单击“查找”:

{ $or: [ { status: "A" }, { qty: { $lt: 30 } } ] }
../../_images/compass-find-filter-or.png
cursor = db.inventory.find(
    {"$or": [{"status": "A"}, {"qty": {"$lt": 30}}]})
findIterable = collection.find(or(eq("status", "A"), lt("qty", 30)));
const cursor = db.collection('inventory').find({
  $or: [{ status: 'A' }, { qty: { $lt: 30 } }]
});
$cursor = $db->inventory->find([
    '$or' => [
        ['status' => 'A'],
        ['qty' => ['$lt' => 30]],
    ],
]);
cursor = db.inventory.find(
    {"$or": [{"status": "A"}, {"qty": {"$lt": 30}}]})
findPublisher = collection.find(or(eq("status", "A"), lt("qty", 30)));
var builder = Builders<BsonDocument>.Filter;
var filter = builder.Or(builder.Eq("status", "A"), builder.Lt("qty", 30));
var result = collection.Find(filter).ToList();
$cursor = $db->coll("inventory")->find(
    { '$or' => [ { status => "A" }, { qty => { '$lt' => 30 } } ] }
);
client[:inventory].find('$or' => [{ status: 'A' },
                                  { qty: { '$lt' => 30 } }
                                 ])
findObservable = collection.find(or(equal("status", "A"), lt("qty", 30)))
cursor, err := coll.Find(
	context.Background(),
	bson.D{
		{"$or",
			bson.A{
				bson.D{{"status", "A"}},
				bson.D{{"qty", bson.D{{"$lt", 30}}}},
			}},
	})

The operation corresponds to the following SQL statement:该操作对应于以下SQL语句:

SELECT * FROM inventory WHERE status = "A" OR qty < 30

Note

Queries which use comparison operators are subject to Type Bracketing.使用比较运算符的查询受类型括号的约束。

Specify AND as well as OR Conditions指定AND以及OR条件

In the following example, the compound query document selects all documents in the collection where the status equals "A" and either qty is less than ($lt) 30 or item starts with the character p:在以下示例中,复合查询文档选择集合中status"A"qty小于($lt30item以字符p开头的所有文档:

db.inventory.find( {
     status: "A",
     $or: [ { qty: { $lt: 30 } }, { item: /^p/ } ]
} )

Copy the following filter into the Compass query bar and click Find:将以下过滤器复制到Compass查询栏中,然后单击“查找”:

{ status: "A", $or: [ { qty: { $lt: 30 } }, { item: /^p/ } ] }
../../_images/compass-find-filter-and-or.png
cursor = db.inventory.find({
    "status": "A",
    "$or": [{"qty": {"$lt": 30}}, {"item": {"$regex": "^p"}}]})
findIterable = collection.find(
        and(eq("status", "A"),
                or(lt("qty", 30), regex("item", "^p")))
);
const cursor = db.collection('inventory').find({
  status: 'A',
  $or: [{ qty: { $lt: 30 } }, { item: { $regex: '^p' } }]
});
$cursor = $db->inventory->find([
    'status' => 'A',
    '$or' => [
        ['qty' => ['$lt' => 30]],
        // Alternatively: ['item' => new \MongoDB\BSON\Regex('^p')]
        ['item' => ['$regex' => '^p']],
    ],
]);
cursor = db.inventory.find({
    "status": "A",
    "$or": [{"qty": {"$lt": 30}}, {"item": {"$regex": "^p"}}]})
findPublisher = collection.find(
        and(eq("status", "A"),
                or(lt("qty", 30), regex("item", "^p")))
);
var builder = Builders<BsonDocument>.Filter;
var filter = builder.And(
    builder.Eq("status", "A"),
    builder.Or(builder.Lt("qty", 30), builder.Regex("item", new BsonRegularExpression("^p"))));
var result = collection.Find(filter).ToList();
$cursor = $db->coll("inventory")->find(
    {
        status => "A",
        '$or'  => [ { qty => { '$lt' => 30 } }, { item => { '$regex' => "^p" } } ]
    }
);
client[:inventory].find(status: 'A',
                        '$or' => [{ qty: { '$lt' => 30 } },
                                  { item: { '$regex' => BSON::Regexp::Raw.new('^p') } }
                        ])
findObservable = collection.find(and(
  equal("status", "A"),
  or(lt("qty", 30), regex("item", "^p")))
)
cursor, err := coll.Find(
	context.Background(),
	bson.D{
		{"status", "A"},
		{"$or", bson.A{
			bson.D{{"qty", bson.D{{"$lt", 30}}}},
			bson.D{{"item", primitive.Regex{Pattern: "^p", Options: ""}}},
		}},
	})

The operation corresponds to the following SQL statement:该操作对应于以下SQL语句:

SELECT * FROM inventory WHERE status = "A" AND ( qty < 30 OR item LIKE "p%")

Note

MongoDB supports regular expressions $regex queries to perform string pattern matches.MongoDB支持正则表达式$regex查询来执行字符串模式匹配。

Additional Query Tutorials附加查询教程

For additional query examples, see:有关其他查询示例,请参阅:

Behavior行为

Cursor游标

The db.collection.find() method returns a cursor to the matching documents.db.collection.find()方法将游标返回到匹配的文档。

The MongoDB Compass Find operation opens a cursor to the matching documents of the collection based on the find query.MongoDB Compass Find操作根据Find查询打开指向集合的匹配文档的游标

For more information on sampling in MongoDB Compass, see the Compass FAQ.有关MongoDB Compass中采样的更多信息,请参阅Compass常见问题解答

The pymongo.collection.Collection.find() method returns a cursor to the matching documents. See the PyMongo documentation for iterating over a cursor.

The com.mongodb.client.MongoCollection.find method returns an instance of the com.mongodb.client.FindIterable interface.

The Collection.find() method returns a cursor.

The MongoDB\Collection::find() method returns a cursor to the matching documents. See the MongoDB PHP Library documentation for iterating over a cursor.

The MongoCollection.Find() method returns a cursor to the matching documents. See the MongoDB C# driver documentation for iterating over a cursor.

The MongoDB::Collection::find() method returns a cursor to the matching documents. See the MongoDB Perl driver documentation for iterating over a cursor.

The Mongo::Collection#find() method returns a CollectionView, which is an Enumerable. A Cursor is created when the View is enumerated; for example, by calling #to_enum() on the View. See the Ruby driver API documentation for iterating over a cursor.

The collection.find() method returns the find Observable.

The Collection.Find function returns a Cursor to the matching documents. See the Cursor documentation for more information.

Read Isolation读隔离

New in version 3.2.版本3.2中的新功能。

For reads to replica sets and replica set shards, read concern allows clients to choose a level of isolation for their reads. 对于副本集和副本集碎片的读取,读关注点允许客户端为其读取选择隔离级别。For more information, see Read Concern.有关更多信息,请参阅读关注点

Additional Methods附加方法

The following methods can also read documents from a collection:以下方法也可以从集合中读取文档:

Note

The db.collection.findOne() method also performs a read operation to return a single document. db.collection.findOne()方法还执行读取操作以返回单个文档。Internally, the db.collection.findOne() method is the db.collection.find() method with a limit of 1.在内部,db.collection.findOne()方法是限制为1的db.collection.find()方法。

Additional Options附加选项

In addition to filter, MongoDB Compass also allows the following options to be passed to the query bar:除了filter,MongoDB Compass还允许将以下选项传递到查询栏:

Project Specify which fields to return in the resulting data.指定要在结果数据中返回的字段。
Sort Specify the sort order of the returned documents.指定返回文档的排序顺序。
Skip Specify the first n-number of document to skip before returning the result set.指定返回结果集之前要跳过的第一个n个文档编号。
Limit Specify the maximum number of documents to return.指定要返回的最大文档数。

Additional Methods附加方法

The following methods can also read documents from a collection:以下方法也可以从集合中读取文档:

Note

The pymongo.collection.Collection.find_one() method also performs a read operation to return a single document. Internally, the pymongo.collection.Collection.find_one() method is the pymongo.collection.Collection.find() method with a limit of 1.

Additional Methods附加方法

The following methods can also read documents from a collection:以下方法也可以从集合中读取文档:

Additional Methods附加方法

The following methods can also read documents from a collection:以下方法也可以从集合中读取文档:

Note

The Collection.findOne() method also performs a read operation to return a single document. Collection.findOne()方法还执行读取操作以返回单个文档。Internally, the Collection.findOne() method is the Collection.find() method with a limit of 1.在内部,Collection.findOne()方法是限制为1的Collection.find()方法。

Additional Methods

The following methods can also read documents from a collection:

Note

The MongoDB\Collection::findOne() method also performs a read operation to return a single document. Internally, the MongoDB\Collection::findOne() method is the MongoDB\Collection::find() method with a limit of 1.

Additional Methods

The following methods can also read documents from a collection:

Additional Methods

The following methods can also read documents from a collection:

Note

The MongoCollection.FindOne() method also performs a read operation to return a single document. Internally, the MongoCollection.FindOne() method is the MongoCollection.Find() method with a limit of 1.

Additional Methods

The following methods can also read documents from a collection:

Note

The MongoDB::Collection::find_one() method also performs a read operation to return a single document. Internally, the MongoDB::Collection::find_one() method is the MongoDB::Collection::find() method with a limit of 1.

Additional Methods

The following methods can also read documents from a collection:

Additional Methods

The following methods can also read documents from a collection:

Additional Methods

The following methods can also read documents from a collection: