OPTIONS
翻译或纠错本页面

db.collection.find()

说明

db.collection.find(<criteria>, <projection>)

查询一个集合中的文档记录,并返回结果集的游标 ( cursor ). [1]

Parameter Type Description
criteria document Optional. Specifies selection criteria 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 using projection operators. To return all fields in the matching document, omit this parameter.
返回:一个按查询条件匹配到的文档记录集的游标 ( cursor ) 。当 find() 方法 “返回文档记录集,” 这个方法实际上返回了一个文档记录集的游标。如果 projection 参数被指定了,匹配到的结果集会只包含 projection 指定的字段和 _id 字段。可以按自己的意愿排除 _id 字段。在 mongo 命令行中执行 find() 操作会立刻自动迭代游标并显示最前面的20条文档记录。输入 it 命令继续迭代游标。使用驱动来取出返回的文档记录,请在各开发语言的驱动列表 ( driver language ) 中选择适合的游标处理机制。

The projection parameter takes a document of the following form:

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

The <boolean> value can be any of the following:

  • 1true 表示包含这个字段。如果没有在 projection 参数中明确指定是否需要返回 _id 字段, find() 方法总是会包含 _id 字段。

  • 0false 不包含这个字段。

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

[1]

db.collection.find() 是一个封装,它封装了更加正式的查询结构中 $query 运算符的功能。

示例

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

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

子文档查询

精确匹配子文档的查询

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

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

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

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

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

用子文档中的字段查询

下面的操作会返回 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 } )

指定需要排除的字段

下面这个操作会查询 bios 集合 并返回 除了 name 子文档中的 first 字段 和 birth 字段以外的所有字段。

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

指定排除 _id 字段

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

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

返回的文档记录集中包含 除了 _idqty 以外的所有字段:

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

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

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

在数组和子文档中应用

下面这个操作会返回 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 up to 20 times to access up to the first 20 documents that match the query. You can use the DBQuery.shellBatchSize to change the number of iterations. See 标记 and Cursor Behaviors. To iterate manually, assign the returned cursor to a variable using the var keyword.

使用变量

下面这个例子是用 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() 方法与SQL语句中的 ORDER BY 语句相对应。

定义返回的文档记录条数

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

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

limit() 方法与SQL语句中的 LIMIT 语句相对应。

设置结果集的起始点

skip() 方法来控制返回的记录集的起始位置。下面这个操作会跳过 bios 集合 中的前 5 个文档记录并返回剩余的文档记录:

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

联合使用游标方法

链式调用游标方法,如下例:

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

无论 limit() 方法和 sort() 方法哪个在前,发向服务器的请求都会遵循这个规则,处理查询和处理 sort() 指令在同一个对象中完成。因此无论操作链中的顺序谁前谁后, limit() 指令总是会在 sort() 指令后执行。参见 meta query operators