Query Documents查询文档

选择语言

On this page本页内容


Use the Select your language drop-down menu in the upper-right to set the language of the following examples.使用右上角的“选择语言”下拉菜单设置以下示例的语言。


This page provides examples of query operations using the db.collection.find() method in mongosh. 本页提供了在mongosh中使用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 MongoCollection.Find() method in the MongoDB C# Driver. The examples on this page use the inventory collection. To populate the inventory collection, run the following:

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. To populate the inventory collection, run the following:

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. To populate the inventory collection, run the following:

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

Tip提示

The driver provides com.mongodb.client.model.Filters helper methods to facilitate the creation of filter documents. The examples on this page use these methods to create the filter documents.

The examples on this page use the inventory collection. To populate the inventory collection, run the following:

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. To populate the inventory collection, run the following:

This page provides examples of query operations using the Collection.find() method in the MongoDB Node.js Driver. 本页提供了使用MongoDB Node.js Driver中的Collection.find()方法的查询操作示例。The examples on this page use the inventory collection. To populate the inventory collection, run the following:本页上的示例使用inventory集合。要填充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. To populate the inventory collection, run the following:

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. To populate the inventory collection, run the following:

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. To populate the inventory collection, run the following:

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. To populate the inventory collection, run the following:

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. To populate the inventory collection, run the following:

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.有关在MongoDB Compass中插入文档的说明,请参阅插入文档

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);
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.TODO(), docs)
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' }")
));
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.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",
        },
    ]
)
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'
  }
]);
$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"
        }
    ]
);
$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',
    ],
]);
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",
        },
    ]
)
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()

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. 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. 要选择集合中的所有文档,请将空文档作为查询筛选器参数传递给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:

db.inventory.find( {} )
Compass select all documents in collection
var filter = Builders<BsonDocument>.Filter.Empty;
var result = collection.Find(filter).ToList();
cursor, err := coll.Find(
	context.TODO(),
	bson.D{},
)
FindPublisher<Document> findPublisher = collection.find(new Document());
FindIterable<Document> findIterable = collection.find(new Document());
cursor = db.inventory.find({})
const cursor = db.collection('inventory').find({});
$cursor = $db->coll("inventory")->find( {} );
$cursor = $db->inventory->find([]);
cursor = db.inventory.find({})
client[:inventory].find({})
var findObservable = collection.find(Document())

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.reactivestreams.client.MongoCollection.find.

For more information on the syntax of the method, see 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().

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, construct a filter using the Eq method:

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

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

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

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

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

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:要指定相等条件,请在查询筛选器文档中使用<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:

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

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" }
Query using equality condition
var filter = Builders<BsonDocument>.Filter.Eq("status", "D");
var result = collection.Find(filter).ToList();
cursor, err := coll.Find(
	context.TODO(),
	bson.D{{"status", "D"}},
)
findPublisher = collection.find(eq("status", "D"));
findIterable = collection.find(eq("status", "D"));
cursor = db.inventory.find({"status": "D"})
const cursor = db.collection('inventory').find({ status: 'D' });
$cursor = $db->coll("inventory")->find( { status => "D" } );
$cursor = $db->inventory->find(['status' => 'D']);
cursor = db.inventory.find({"status": "D"})
client[:inventory].find(status: 'D')
findObservable = collection.find(equal("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> }, ... }

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>));

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

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> }, ... }

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>), 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" ] } }
Query using query operators
var filter = Builders<BsonDocument>.Filter.In("status", new[] { "A", "D" });
var result = collection.Find(filter).ToList();
cursor, err := coll.Find(
	context.TODO(),
	bson.D{{"status", bson.D{{"$in", bson.A{"A", "D"}}}}})
findPublisher = collection.find(in("status", "A", "D"));
findIterable = collection.find(in("status", "A", "D"));
cursor = db.inventory.find({"status": {"$in": ["A", "D"]}})
const cursor = db.collection('inventory').find({
  status: { $in: ['A', 'D'] }
});
$cursor = $db->coll("inventory")->find( { status => { '$in' => [ "A", "D" ] } } );
$cursor = $db->inventory->find(['status' => ['$in' => ['A', 'D']]]);
cursor = db.inventory.find({"status": {"$in": ["A", "D"]}})
client[:inventory].find(status: { '$in' => [ 'A', 'D' ]})
findObservable = collection.find(in("status", "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 } }
Query using multiple conditions with AND
var builder = Builders<BsonDocument>.Filter;
var filter = builder.And(builder.Eq("status", "A"), builder.Lt("qty", 30));
var result = collection.Find(filter).ToList();
cursor, err := coll.Find(
	context.TODO(),
	bson.D{
		{"status", "A"},
		{"qty", bson.D{{"$lt", 30}}},
	})
findPublisher = collection.find(and(eq("status", "A"), lt("qty", 30)));
findIterable = collection.find(and(eq("status", "A"), lt("qty", 30)));
cursor = db.inventory.find({"status": "A", "qty": {"$lt": 30}})
const cursor = db.collection('inventory').find({
  status: 'A',
  qty: { $lt: 30 }
});
$cursor = $db->coll("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}})
client[:inventory].find(status: 'A', qty: { '$lt' => 30 })
findObservable = collection.find(and(equal("status", "A"), lt("qty", 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 } } ] }
Query using OR
var builder = Builders<BsonDocument>.Filter;
var filter = builder.Or(builder.Eq("status", "A"), builder.Lt("qty", 30));
var result = collection.Find(filter).ToList();
cursor, err := coll.Find(
	context.TODO(),
	bson.D{
		{"$or",
			bson.A{
				bson.D{{"status", "A"}},
				bson.D{{"qty", bson.D{{"$lt", 30}}}},
			}},
	})
findPublisher = collection.find(or(eq("status", "A"), lt("qty", 30)));
findIterable = collection.find(or(eq("status", "A"), lt("qty", 30)));
cursor = db.inventory.find({"$or": [{"status": "A"}, {"qty": {"$lt": 30}}]})
const cursor = db.collection('inventory').find({
  $or: [{ status: 'A' }, { qty: { $lt: 30 } }]
});
$cursor = $db->coll("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}}]})
client[:inventory].find('$or' => [{ status: 'A' },
                                  { qty: { '$lt' => 30 } }
                                 ])
findObservable = collection.find(or(equal("status", "A"), lt("qty", 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指定ANDOR条件

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 oritem 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/ } ] }
Query using AND as well as OR
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, err := coll.Find(
	context.TODO(),
	bson.D{
		{"status", "A"},
		{"$or", bson.A{
			bson.D{{"qty", bson.D{{"$lt", 30}}}},
			bson.D{{"item", primitive.Regex{Pattern: "^p", Options: ""}}},
		}},
	})
findPublisher = collection.find(
        and(eq("status", "A"),
                or(lt("qty", 30), regex("item", "^p")))
);
findIterable = collection.find(
        and(eq("status", "A"),
                or(lt("qty", 30), regex("item", "^p")))
);
cursor = db.inventory.find(
    {"status": "A", "$or": [{"qty": {"$lt": 30}}, {"item": {"$regex": "^p"}}]}
)
const cursor = db.collection('inventory').find({
  status: 'A',
  $or: [{ qty: { $lt: 30 } }, { item: { $regex: '^p' } }]
});
$cursor = $db->coll("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"}}]}
)
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")))
)

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 “查找”操作打开一个游标,指向基于查找查询的集合的匹配文档。

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

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

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

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

The Collection.find() method returns a cursor.Collection.find()方法返回一个游标

The MongoDB::Collection::find() method returns a cursor to the matching documents. See the MongoDB Perl driver documentation for iterating over 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 pymongo.collection.Collection.find method returns a cursor to the matching documents. See the PyMongo 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_a() or #each(). You can also get an Enumerator 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.

Read Isolation读取隔离

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.有关更多信息,请参阅读取关注

←  Insert MethodsQuery on Embedded/Nested Documents →