翻译或纠错本页面

db.collection.find()

On this page

说明

db.collection.find(query, projection)

Selects documents in a collection and returns a cursor to the selected documents.

Parameter Type Description
query document Optional. Specifies selection filter using query operators. To return all documents in a collection, omit this parameter or pass an empty document ({}).
projection document Optional. Specifies the fields to return in the documents that match the query filter. To return all fields in the matching documents, omit this parameter. For details, see Projection.
返回:一个按查询条件匹配到的文档记录集的游标 cursor 。当 find() 方法 “返回文档记录集,” 这个方法实际上返回了一个文档记录集的游标。

Behavior

Projection

使用驱动来取出返回的文档记录,请在 :doc:` 各开发语言的驱动列表 </applications/drivers>` 中选择适合的游标处理机制。

{ field1: <value>, field2: <value> ... }

The <value> can be any of the following:

注解

For the _id field, you do not have to explicitly specify _id: 1 to return the _id field. The find() method always returns the _id field unless you specify _id: 0 to suppress the field.

A projection cannot contain both include and exclude specifications, except for the exclusion of the _id field. In projections that explicitly include fields, the _id field is the only field that you can explicitly exclude.

Cursor Handling

一个 projection不能同时 有”包含”和”排除”这两种规则,除非只是排除 _id 字段。在指定 需要包含 的字段的时,只有 _id 字段可以同时指定成 需要排除

To access the returned documents with a driver, use the appropriate cursor handling mechanism for the driver language.

Read Concern

To specify the read concern for db.collection.find(), use the cursor.readConcern() method.

Type Bracketing

MongoDB treats some data types as equivalent for comparison purposes. For instance, numeric types undergo conversion before comparison. For most data types, however, comparison operators only perform comparisons on documents where the BSON type of the target field matches the type of the query operand. Consider the following collection:

{ "_id": "apples", "qty": 5 }
{ "_id": "bananas", "qty": 7 }
{ "_id": "oranges", "qty": { "in stock": 8, "ordered": 12 } }
{ "_id": "avocados", "qty": "fourteen" }

The following query uses $gt to return documents where the value of qty is greater than 4.

db.collection.find( { qty: { $gt: 4 } } )

The query returns the following documents:

{ "_id": "apples", "qty": 5 }
{ "_id": "bananas", "qty": 7 }

The document with _id equal to "avocados" is not returned because its qty value is of type string while the $gt operand is of type integer.

The document with _id equal to "oranges" is not returned because its qty value is of type object.

注解

To enforce data types in a collection, use Document Validation.

示例

取出一个集合中的所有文档记录

The find() method with no parameters returns all documents from a collection and returns all fields for the documents. For example, the following operation returns all documents in the bios collection:

db.bios.find()

查找满足查询条件的文档记录

如果想要查找满足一组筛选条件的文档记录,可以用 find() 方法和 <criteria> 参数 。下面这个操作会返回 products 集合中所有 qty 大于25的记录:

db.products.find( { qty: { $gt: 25 } } )

“等于”条件查询

下面这个操作会返回 bios 集合_id 等于5的文档记录。

db.bios.find( { _id: 5 } )

带运算符的查询

下面这个操作会返回 bios 集合_id 等于 5ObjectId("507c35dd8fada716c89d0013") 的文档记录:

db.bios.find(
   {
      _id: { $in: [ 5,  ObjectId("507c35dd8fada716c89d0013") ] }
   }
)

区间条件查询

用比较运算符联合指定区间。下面的操作会返回 fieldvalue1value2 之间的文档记录:

db.collection.find( { field: { $gt: value1, $lt: value2 } } );

查询包含数组的字段

如果一个字段包含数组并且查询中有多个条件运算符,字段中数组里的值有一个或多个满足查询条件的都会匹配成功。

创建一个 students 集合,集合里有下面这些文档记录:

{ "_id" : 1, "score" : [ -1, 3 ] }
{ "_id" : 2, "score" : [ 1, 5 ] }
{ "_id" : 3, "score" : [ 5, 5 ] }

下面这个查询:

db.students.find( { score: { $gt: 0, $lt: 2 } } )

能匹配上下面这些文档记录:

{ "_id" : 1, "score" : [ -1, 3 ] }
{ "_id" : 2, "score" : [ 1, 5 ] }

_id 等于 1 的这条文档记录中, score: [ -1, 3 ] 满足条件是因为 -1 这个元素满足 $lt: 2 这个条件并且 3 这个值满足 $gt: 0 这个条件。

_id 等于 2 的这条文档记录中, score: [ 1, 5 ] 满足条件是因为 1 这个元素同时满足 $lt: 2$gt: 0 这两个条件。

数组查询

查询一个数组元素

下面这个操作会返回 bios 集合contribs 这个字段包含 "UNIX" 这个元素的所有文档记录:

db.bios.find( { contribs: "UNIX" } )

查询文档组成的数组

下面这个操作会返回 bios 集合awards 这个由子文档组成的数组字段中,子文档的 award 等于 "Turing Award" 并且子文档的 year 大于1980的文档记录:

db.bios.find(
   {
      awards: {
                $elemMatch: {
                     award: "Turing Award",
                     year: { $gt: 1980 }
                }
      }
   }
)

Query Embedded Documents

Query Exact Matches on Embedded Documents

下面这个操作会返回 bios 集合 中子文档 name 等于 { first: "Yukihiro", last: "Matsumoto" } 的文档记录,命令如下:

db.bios.find(
    {
      name: {
              first: "Yukihiro",
              last: "Matsumoto"
            }
    }
)

The name field must match the embedded document exactly. The query does not match documents with the following name fields:

{
   first: "Yukihiro",
   aka: "Matz",
   last: "Matsumoto"
}

{
   last: "Matsumoto",
   first: "Yukihiro"
}

Query Fields of an Embedded Document

下面的操作会返回 bios 集合name 字段的子文档中包含字段 first 值为 "Yukihiro" 并且子文档中包含字段 last 值为 "Matsumoto" 的文档记录。查询条件中用点号分隔法 dot notation 来给子文档中的字段添加条件。

db.bios.find(
   {
     "name.first": "Yukihiro",
     "name.last": "Matsumoto"
   }
)

这个查询会匹配 name 字段中的子文档里 first 字段值为 "Yukihiro" 并且子文档里 last 字段的值为 "Matsumoto" 的文档记录。例如, 文档记录中 name 字段的值是下面任何一个,查询都会匹配到这些文档。

{
  first: "Yukihiro",
  aka: "Matz",
  last: "Matsumoto"
}

{
  last: "Matsumoto",
  first: "Yukihiro"
}

指定返回字段

The projection parameter specifies which fields to return. The parameter contains either include or exclude specifications, not both, unless the exclude is for the _id field.

指定需要返回的字段

下面这个操作会返回 products 集合中 qty 大于 25 的文档记录,返回的文档记录中只包含 _id, itemqty 这几个字段:

db.products.find( { qty: { $gt: 25 } }, { item: 1, qty: 1 } )

操作返回的结果如下:

{ "_id" : 11, "item" : "pencil", "qty" : 50 }
{ "_id" : ObjectId("50634d86be4617f17bb159cd"), "item" : "bottle", "qty" : 30 }
{ "_id" : ObjectId("50634dbcbe4617f17bb159d0"), "item" : "paper", "qty" : 100 }

下面这个操作会返回 bios 集合 中的所有文档记录,返回的文档记录中只包含 namecontribs_id 这几个字段:

db.bios.find( { }, { name: 1, contribs: 1 } )

指定需要排除的字段

The following operation queries the bios collection and returns all fields except the first field in the name embedded document and the birth field:

db.bios.find(
   { contribs: 'OOP' },
   { 'name.first': 0, birth: 0 }
)

Explicitly Exclude the _id Field

下面这个操作会在查询结果中排除 _idqty 字段:

db.products.find( { qty: { $gt: 25 } }, { _id: 0, qty: 0 } )

The documents in the result set contain all fields except the _id and qty fields:

{ "item" : "pencil", "type" : "no.2" }
{ "item" : "bottle", "type" : "blue" }
{ "item" : "paper" }

下面这个操作会取回 bios 集合 中的所有记录,记录中只包含 namecontribs 字段:

db.bios.find(
   { },
   { name: 1, contribs: 1, _id: 0 }
)

On Arrays and Embedded Documents

下面这个操作会返回 bios 集合name 子文档中的 last 字段和 contribs 数组的前2个元素:

db.bios.find(
   { },
   {
     _id: 0,
     'name.last': 1,
     contribs: { $slice: 2 }
   }
)

对返回的游标进行迭代

The find() method returns a cursor to the results.

In the mongo shell, if the returned cursor is not assigned to a variable using the var keyword, the cursor is automatically iterated to access up to the first 20 documents that match the query. You can set the DBQuery.shellBatchSize variable to change the number of automatically iterated documents.

To manually iterate over the results, assign the returned cursor to a variable with the var keyword, as shown in the following sections.

使用变量

下面这个例子是用 myCursor 变量来迭代完返回的游标并把匹配到的文档记录打印出来:

var myCursor = db.bios.find( );

myCursor

使用 next() 方法

下面这个例子是用游标的 next() 方法来取回文档记录:

var myCursor = db.bios.find( );

var myDocument = myCursor.hasNext() ? myCursor.next() : null;

if (myDocument) {
    var myName = myDocument.name;
    print (tojson(myName));
}

在需要打印的时候也可以用 printjson() 方法来代替 print(tojson())

if (myDocument) {
   var myName = myDocument.name;
   printjson(myName);
}

使用 forEach() 方法

下面这个例子是用游标的 forEach() 方法来迭代游标并取出文档记录:

var myCursor = db.bios.find( );

myCursor.forEach(printjson);

修改游标行为

The mongo shell and the drivers provide several cursor methods that call on the cursor returned by the find() method to modify its behavior.

给结果集中的文档记录排序

The sort() method orders the documents in the result set. The following operation returns documents in the bios collection sorted in ascending order by the name field:

db.bios.find().sort( { name: 1 } )

sort() corresponds to the ORDER BY statement in SQL.

定义返回的文档记录条数

limit() 方法来设置返回结果集中的记录数。下面的操作会返回 bios 集合 中的最多 5 个文档记录:

db.bios.find().limit( 5 )

limit() corresponds to the LIMIT statement in SQL.

设置结果集的起始点

The skip() method controls the starting point of the results set. The following operation skips the first 5 documents in the bios collection and returns all remaining documents:

db.bios.find().skip( 5 )

Specify Collation

Collation allows users to specify language-specific rules for string comparison, such as rules for lettercase and accent marks.

The collation method specifies the collation for the db.collection.find() operation.

db.bios.find( { "name.last": "hopper" } ).collation( { locale: "en_US", strength: 1 } )

Combine Cursor Methods

The following statements chain cursor methods limit() and sort():

db.bios.find().sort( { name: 1 } ).limit( 5 )
db.bios.find().limit( 5 ).sort( { name: 1 } )

The two statements are equivalent; i.e. the order in which you chain the limit() and the sort() methods is not significant. Both statements return the first five documents, as determined by the ascending sort order on ‘name’.