Query Method

MongoDB provides the db.collection.find() method to read documents from a collection. The db.collection.find() method returns a cursor to the matching documents.

db.collection.find( <query filter>, <projection> )

For the db.collection.find() method, you can specify the following optional fields:

  • query filter to specify which documents to return.
  • a query projection to specifies which fields from the matching documents to return. The projection limits the amount of data that MongoDB returns to the client over the network.

You can optionally add a cursor modifier to impose limits, skips, and sort orders. The order of documents returned by a query is not defined unless you specify a sort().

Example Collection

The examples on this page use the db.collection.find() method in the mongo shell. In the mongoshell, if the returned cursor is not assigned to a variable using the var keyword, then the cursor is automatically iterated up to 20 times to print up to the first 20 documents in the results.

To populate the users collection referenced in the examples, run the following in mongo shell:

NOTE: If the users collection already contains documents with the same _id values, you need to drop the collection (db.users.drop()) before inserting the example documents.

db.users.insertMany(
[
{
_id: 1,
name: "sue",
age: 19,
type: 1,
status: "P",
favorites: { artist: "Picasso", food: "pizza" },
finished: [ 17, 3 ],
badges: [ "blue", "black" ],
points: [
{ points: 85, bonus: 20 },
{ points: 85, bonus: 10 }
]
},
{
_id: 2,
name: "bob",
age: 42,
type: 1,
status: "A",
favorites: { artist: "Miro", food: "meringue" },
finished: [ 11, 25 ],
badges: [ "green" ],
points: [
{ points: 85, bonus: 20 },
{ points: 64, bonus: 12 }
]
},
{
_id: 3,
name: "ahn",
age: 22,
type: 2,
status: "A",
favorites: { artist: "Cassatt", food: "cake" },
finished: [ 6 ],
badges: [ "blue", "red" ],
points: [
{ points: 81, bonus: 8 },
{ points: 55, bonus: 20 }
]
},
{
_id: 4,
name: "xi",
age: 34,
type: 2,
status: "D",
favorites: { artist: "Chagall", food: "chocolate" },
finished: [ 5, 11 ],
badges: [ "red", "black" ],
points: [
{ points: 53, bonus: 15 },
{ points: 51, bonus: 15 }
]
},
{
_id: 5,
name: "xyz",
age: 23,
type: 2,
status: "D",
favorites: { artist: "Noguchi", food: "nougat" },
finished: [ 14, 6 ],
badges: [ "orange" ],
points: [
{ points: 71, bonus: 20 }
]
},
{
_id: 6,
name: "abc",
age: 43,
type: 1,
status: "A",
favorites: { food: "pizza", artist: "Picasso" },
finished: [ 18, 12 ],
badges: [ "black", "blue" ],
points: [
{ points: 78, bonus: 8 },
{ points: 57, bonus: 7 }
]
}
]
)

Select All Documents in a Collection

An empty query filter document ({}) selects all documents in the collection:

db.users.find( {} )

Omitting a query filter document to the db.collection.find() is equivalent to specifying an empty query document. As such, the following operation is equivalent to the previous operation:

db.users.find()

Specify Query Filter Conditions

Specify Equality Condition

query filter document can specify equality condition with <field>:<value> expressions to select all documents that contain the <field> with the specified <value>:

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

The following example retrieves from the users collection all documents where the status field has the value "A":

db.users.find( { status: "A" } )

Specify Conditions Using Query Operators

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

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

The following example retrieves all documents from the users collection where status equals either "P"or "D":

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

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.

Refer to the Query and Projection Operators document for the complete list of query operators.

Specify AND Conditions

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.

The following example retrieves all documents in the users collection where the status equals "A" and age is less than ($lt30:

db.users.find( { status: "A", age: { $lt: 30 } } )

See comparison operators for other comparison operators.

Specify OR Conditions

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.

The following example retrieves all documents in the collection where the status equals "A" or age is less than ($lt30:

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

NOTE: Queries which use comparison operators are subject to Type Bracketing.

Specify AND as well as OR Conditions

With additional clauses, you can specify precise conditions for matching documents.

In the following example, the compound query document selects all documents in the collection where the``status`` equals "A" and either age is less than than ($lt30 or type equals 1:

db.users.find(
{
status: "A",
$or: [ { age: { $lt: 30 } }, { type: 1 } ]
}
)

Query on Embedded Documents

When the field holds an embedded document, a query can either specify an exact match on the embedded document or specify a match by individual fields in the embedded document using the dot notation.

Exact Match on the Embedded Document

To specify an exact equality match on the whole embedded document, use the query document { <field>: <value> } where <value> is the document to match. Equality matches on an embedded document require an exact match of the specified <value>, including the field order.

In the following example, the query matches all documents where the favorites field is an embedded document that contains only the fields artist equal to "Picasso" and food equal to "pizza", in that order:

db.users.find( { favorites: { artist: "Picasso", food: "pizza" } } )

Equality Match on Fields within an Embedded Document

Use the dot notation to match by specific fields in an embedded document. Equality matches for specific fields in an embedded document will select documents in the collection where the embedded document contains the specified fields with the specified values. The embedded document can contain additional fields.

In the following example, the query uses the dot notation to match all documents where the favorites field is an embedded document that includes the field artist equal to "Picasso" and may contain other fields:

db.users.find( { "favorites.artist": "Picasso" } )

Query on Arrays

When the field holds an array, you can query for an exact array match or for specific values in the array. If the array holds embedded documents, you can query for specific fields in the embedded documents using dot notation.

If you specify multiple conditions using the $elemMatch operator, the array must contain at least one element that satisfies all the conditions. See Single Element Satisfies the Criteria.

If you specify multiple conditions without using the $elemMatch operator, then some combination of the array elements, not necessarily a single element, must satisfy all the conditions; i.e. different elements in the array can satisfy different parts of the conditions. See Combination of Elements Satisfies the Criteria.

Exact Match on an Array

To specify equality match on an array, use the query document { <field>: <value> } where <value>is the array to match. Equality matches on the array require that the array field match exactly the specified <value>, including the element order.

The following example queries for all documents where the field badges is an array that holds exactly two elements, "blue", and "black", in this order:

db.users.find( { badges: [ "blue", "black" ] } )

The query matches the following document:

{
"_id" : 1,
"name" : "sue",
"age" : 19,
"type" : 1,
"status" : "P",
"favorites" : { "artist" : "Picasso", "food" : "pizza" },
"finished" : [ 17, 3 ]
"badges" : [ "blue", "black" ],
"points" : [ { "points" : 85, "bonus" : 20 }, { "points" : 85, "bonus" : 10 } ]
}

Match an Array Element

Equality matches can specify a single element in the array to match. These specifications match if the array contains at least one element with the specified value.

The following example queries for all documents where badges is an array that contains "black" as one of its elements:

db.users.find( { badges: "black" } )

The query matches the following documents:

{
"_id" : 1,
"name" : "sue",
"age" : 19,
"type" : 1,
"status" : "P",
"favorites" : { "artist" : "Picasso", "food" : "pizza" },
"finished" : [ 17, 3 ]
"badges" : [ "blue", "black" ],
"points" : [ { "points" : 85, "bonus" : 20 }, { "points" : 85, "bonus" : 10 } ]
}
{
"_id" : 4,
"name" : "xi",
"age" : 34,
"type" : 2,
"status" : "D",
"favorites" : { "artist" : "Chagall", "food" : "chocolate" },
"finished" : [ 5, 11 ],
"badges" : [ "red", "black" ],
"points" : [ { "points" : 53, "bonus" : 15 }, { "points" : 51, "bonus" : 15 } ]
}
{
"_id" : 6,
"name" : "abc",
"age" : 43,
"type" : 1,
"status" : "A",
"favorites" : { "food" : "pizza", "artist" : "Picasso" },
"finished" : [ 18, 12 ],
"badges" : [ "black", "blue" ],
"points" : [ { "points" : 78, "bonus" : 8 }, { "points" : 57, "bonus" : 7 } ]
}

Match a Specific Element of an Array

Equality matches can specify equality matches for an element at a particular index or position of the array using the dot notation.

In the following example, the query uses the dot notation to match all documents where the badges is an array that contains "black" as the first element:

db.users.find( { "badges.0": "black" } )

The operation returns the following document:

{
"_id" : 6,
"name" : "abc",
"age" : 43,
"type" : 1,
"status" : "A",
"favorites" : { "food" : "pizza", "artist" : "Picasso" },
"finished" : [ 18, 12 ],
"badges" : [ "black", "blue" ],
"points" : [ { "points" : 78, "bonus" : 8 }, { "points" : 57, "bonus" : 7 } ]
}

Specify Multiple Criteria for Array Elements

Single Element Satisfies the Criteria

Use $elemMatch operator to specify multiple criteria on the elements of an array such that at least one array element satisfies all the specified criteria.

The following example queries for documents where the finished array contains at least one element that is greater than ($gt15 and less than ($lt20:

db.users.find( { finished: { $elemMatch: { $gt: 15, $lt: 20 } } } )

The operation returns the following documents, whose finished array contains at least one element which meets both criteria:

{
"_id" : 1,
"name" : "sue",
"age" : 19,
"type" : 1,
"status" : "P",
"favorites" : { "artist" : "Picasso", "food" : "pizza" },
"finished" : [ 17, 3 ]
"badges" : [ "blue", "black" ],
"points" : [ { "points" : 85, "bonus" : 20 }, { "points" : 85, "bonus" : 10 } ]
}
{
"_id" : 6,
"name" : "abc",
"age" : 43,
"type" : 1,
"status" : "A",
"favorites" : { "food" : "pizza", "artist" : "Picasso" },
"finished" : [ 18, 12 ],
"badges" : [ "black", "blue" ],
"points" : [ { "points" : 78, "bonus" : 8 }, { "points" : 57, "bonus" : 7 } ]
}

Combination of Elements Satisfies the Criteria

The following example queries for documents where the finished array contains elements that in some combination satisfy the query conditions; e.g., one element can satisfy the greater than 15 condition and another element can satisfy the less than 20 condition, or a single element can satisfy both:

db.users.find( { finished: { $gt: 15, $lt: 20 } } )

The operation returns the following documents:

{
"_id" : 1,
"name" : "sue",
"age" : 19,
"type" : 1,
"status" : "P",
"favorites" : { "artist" : "Picasso", "food" : "pizza" },
"finished" : [ 17, 3 ]
"badges" : [ "blue", "black" ],
"points" : [ { "points" : 85, "bonus" : 20 }, { "points" : 85, "bonus" : 10 } ]
}
{
"_id" : 2,
"name" : "bob",
"age" : 42,
"type" : 1,
"status" : "A",
"favorites" : { "artist" : "Miro", "food" : "meringue" },
"finished" : [ 11, 20 ],
"badges" : [ "green" ],
"points" : [ { "points" : 85, "bonus" : 20 }, { "points" : 64, "bonus" : 12 } ]
}
{
"_id" : 6,
"name" : "abc",
"age" : 43,
"type" : 1,
"status" : "A",
"favorites" : { "food" : "pizza", "artist" : "Picasso" },
"finished" : [ 18, 12 ],
"badges" : [ "black", "blue" ],
"points" : [ { "points" : 78, "bonus" : 8 }, { "points" : 57, "bonus" : 7 } ]
}

Array of Embedded Documents

Match a Field in the Embedded Document Using the Array Index

If you know the array index of the embedded document, you can specify the document using the embedded document’s position using the dot notation.

The following example selects all documents where the points contains an array whose first element (i.e. index is 0) is a document that contains the field points whose value is less than or equal to 55:

db.users.find( { 'points.0.points': { $lte: 55 } } )

The operation returns the following documents:

{
"_id" : 4,
"name" : "xi",
"age" : 34,
"type" : 2,
"status" : "D",
"favorites" : { "artist" : "Chagall", "food" : "chocolate" },
"finished" : [ 5, 11 ],
"badges" : [ "red", "black" ],
"points" : [ { "points" : 53, "bonus" : 15 }, { "points" : 51, "bonus" : 15 } ]
}

Match a Field Without Specifying Array Index

If you do not know the index position of the document in the array, concatenate the name of the field that contains the array, with a dot (.) and the name of the field in the embedded document.

The following example selects all documents where the points is an array with at least one embedded document that contains the field points whose value is less than or equal to 55:

db.users.find( { 'points.points': { $lte: 55 } } )

The operation returns the following documents:

{
"_id" : 3,
"name" : "ahn",
"age" : 22,
"type" : 2,
"status" : "A",
"favorites" : { "artist" : "Cassatt", "food" : "cake" },
"finished" : [ 6 ],
"badges" : [ "blue", "red" ],
"points" : [ { "points" : 81, "bonus" : 8 }, { "points" : 55, "bonus" : 20 } ]
}
{
"_id" : 4,
"name" : "xi",
"age" : 34,
"type" : 2,
"status" : "D",
"favorites" : { "artist" : "Chagall", "food" : "chocolate" },
"finished" : [ 5, 11 ],
"badges" : [ "red", "black" ],
"points" : [ { "points" : 53, "bonus" : 15 }, { "points" : 51, "bonus" : 15 } ]
}

Specify Multiple Criteria for Array of Documents

Single Element Satisfies the Criteria

Use $elemMatch operator to specify multiple criteria on an array of embedded documents such that at least one embedded document satisfies all the specified criteria.

The following example queries for documents where the points array has at least one embedded document that contains both the field points less than or equal to 70 and the field bonus equal to 20:

db.users.find( { points: { $elemMatch: { points: { $lte: 70 }, bonus: 20 } } } )

The operation returns the following document:

{
"_id" : 3,
"name" : "ahn",
"age" : 22,
"type" : 2,
"status" : "A",
"favorites" : { "artist" : "Cassatt", "food" : "cake" },
"finished" : [ 6 ],
"badges" : [ "blue", "red" ],
"points" : [ { "points" : 81, "bonus" : 8 }, { "points" : 55, "bonus" : 20 } ]
}

Combination of Elements Satisfies the Criteria

The following example queries for documents where the points array contains elements that in some combination satisfy the query conditions; e.g. one element satisfies the points less than or equal to 70condition and another element satisfies the bonus equal to 20 condition, or a single element satisfies both criteria:

db.users.find( { "points.points": { $lte: 70 }, "points.bonus": 20 } )

The query returns the following documents:

{
"_id" : 2,
"name" : "bob",
"age" : 42,
"type" : 1,
"status" : "A",
"favorites" : { "artist" : "Miro", "food" : "meringue" },
"finished" : [ 11, 20 ],
"badges" : [ "green" ],
"points" : [ { "points" : 85, "bonus" : 20 }, { "points" : 64, "bonus" : 12 } ]
}
{
"_id" : 3,
"name" : "ahn",
"age" : 22,
"type" : 2,
"status" : "A",
"favorites" : { "artist" : "Cassatt", "food" : "cake" },
"finished" : [ 6 ],
"badges" : [ "blue", "red" ],
"points" : [ { "points" : 81, "bonus" : 8 }, { "points" : 55, "bonus" : 20 } ]
}

Additional Methods

The following methods can also read documents from a collection:

Read Isolation

New in version 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.

MongoDB - MongoDB CRUD Operations, Query Documents的更多相关文章

  1. MongoDB - MongoDB CRUD Operations, Query Documents, Iterate a Cursor in the mongo Shell

    The db.collection.find() method returns a cursor. To access the documents, you need to iterate the c ...

  2. MongoDB - MongoDB CRUD Operations, Query Documents, Project Fields to Return from Query

    By default, queries in MongoDB return all fields in matching documents. To limit the amount of data ...

  3. MongoDB - MongoDB CRUD Operations, Query Documents, Query for Null or Missing Fields

    Different query operators in MongoDB treat null values differently. The examples on this page use th ...

  4. MongoDB - MongoDB CRUD Operations, Delete Documents

    Delete Methods MongoDB provides the following methods to delete documents of a collection: Method De ...

  5. MongoDB - MongoDB CRUD Operations, Insert Documents

    MongoDB provides the following methods for inserting documents into a collection: db.collection.inse ...

  6. MongoDB - MongoDB CRUD Operations, Update Documents

    Update Methods MongoDB provides the following methods for updating documents in a collection: Method ...

  7. MongoDB - MongoDB CRUD Operations

    CRUD operations create, read, update, and delete documents. Create Operations Create or insert opera ...

  8. MongoDB - MongoDB CRUD Operations, Bulk Write Operations

    Overview MongoDB provides clients the ability to perform write operations in bulk. Bulk write operat ...

  9. Mongodb系列- CRUD操作介绍

    ---恢复内容开始--- 一 Create 操作 在MongoDB中,插入操作的目标是一个集合. MongoDB中的所有写入操作在单个文档的层次上都是原子的. For examples, see In ...

随机推荐

  1. 通过javascript完成分页查询功能

    主要思路: 实现分页查询的关键是设置一个页面的最大数据行数和开始行号,代码如下: 最大行数我们设置为常量,不必纠结于他,所以关键就是如何把起始行号设置为变量,让他随着我们点击[上一页]或[下一页]而改 ...

  2. 用CSS让字体在一行内显示不换行(收藏)

    当一行文字超过DIV或者Table的宽度的时候,浏览器中默认是让它换行显示的,如果不想让他换行要怎么办呢? 用CSS让文字在一行内显示不换行的方法   一般的文字截断(适用于内联与块): .text- ...

  3. Object-C基础

    cocoa 类: 传统的写法:Demo.h // // Demo.h // demoClass // // Created by 王 on 13-12-16. // Copyright (c) 201 ...

  4. C# 6与VB 12即将加入模式匹配

    又有一种源自于函数式编程语言中的概念加入了C#和VB的阵营,这就是被称为模式匹配(Pattern Matching)的特性.初看上去,模式匹配的作用类似于一段switch/select语句块,但它的功 ...

  5. 最长公共子序列(LCS问题)

    先简单介绍下什么是最长公共子序列问题,其实问题很直白,假设两个序列X,Y,X的值是ACBDDCB,Y的值是BBDC,那么XY的最长公共子序列就是BDC.这里解决的问题就是需要一种算法可以快速的计算出这 ...

  6. 好记心不如烂笔头之JQuery学习,第二章

    jQuery获取元素不需要担心元素不存在而报错,但是无论怎样 $("#xxx") 是一定会有返回值的,无论存不存在元素,那么依然是要对元素做判断的,判断的方法常见两种 1.看返回的 ...

  7. LINUX CACHE IO THREAD

    http://www.penglixun.com/tech/system/linux_cache_discovery.html http://my.oschina.net/HardySimpson/b ...

  8. SSIS 64位环境访问Oracle11g

    SSIS 为了要能够在64位的机器上面让SSIS存取Oracle,当然需要安装64位的Oracle Provider,但是遇到最大的问题在于SSIS在执行的时候分成两种组件,分别是DTExec.exe ...

  9. 嵌入式设备上运行AllJoyn注意事项

    1. 交叉编译AllJoyn库.编译成功后的文件位于:alljoyn-3.3.0-src\build\linux\arm\debug\dist\目录下: 2. 程序要使用AllJoyn,必须要启动al ...

  10. javascript中的原型和闭包

    定义 //闭包测试 function bbTest() { var local = "这里是本地变量"; //闭包会扩大局部变量的作用域,具备变量一致会存活到函数之外,在函数之外可 ...