By default, queries in MongoDB return all fields in matching documents. To limit the amount of data that MongoDB sends to applications, you can include a projection document in the query operation.

Projection Document

The projection document limits the fields to return for all matching documents. The projection document can specify the inclusion of fields or the exclusion of field and has the following form:

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

The <value> can be any of the following:

  • 1 or true to include the field in the return documents.
  • 0 or false to exclude the field.
  • Expression using a Projection Operators.

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

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.

Example Collection

The examples on this page use the db.collection.find() method in the mongo shell. In the mongo shell, 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 }
]
}
]
)

Return All Fields in Matching Documents

If you specify no projection, the db.collection.find() method returns all fields of all documents that match the query.

The following example retrieves from the users collection all documents where the status equals "A":

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

The matching documents includes all their fields:

{
"_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" : 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 } ]
}

Return the Specified Fields and the _id Field Only

A projection can explicitly include several fields. In the following operation, the db.collection.find()method returns all documents that match the query. In the result set, only the namestatus and, by default, the _id fields return in the matching documents.

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

The operation returns the following documents:

{ "_id" : 2, "name" : "bob", "status" : "A" }
{ "_id" : 3, "name" : "ahn", "status" : "A" }
{ "_id" : 6, "name" : "abc", "status" : "A" }

Return Specified Fields Only

You can remove the _id field from the results by specifying its exclusion in the projection, as in the following example:

db.users.find( { status: "A" }, { name: 1, status: 1, _id: 0 } )

In the result set, only the name and status fields return in the matching documents:

{ "name" : "bob", "status" : "A" }
{ "name" : "ahn", "status" : "A" }
{ "name" : "abc", "status" : "A" }

Return All But the Excluded Field

To exclude a field or multiple fields, instead of listing the fields to include in the matching document, you can use a projection to exclude specific fields as in the following example:

db.users.find( { status: "A" }, { favorites: 0, points: 0 } )

In the result set, the favorites and the points fields do not return in the matching documents:

{
"_id" : 2,
"name" : "bob",
"age" : 42,
"type" : 1,
"status" : "A",
"finished" : [ 11, 25 ],
"badges" : [ "green" ]
}
{
"_id" : 3,
"name" : "ahn",
"age" : 22,
"type" : 2,
"status" : "A",
"finished" : [ 6 ],
"badges" : [ "blue", "red" ]
}
{
"_id" : 6,
"name" : "abc",
"age" : 43,
"type" : 1,
"status" : "A",
"finished" : [ 18, 12 ],
"badges" : [ "black", "blue" ]
}

With the exception of the _id field you cannot combine inclusion and exclusion statements in projection documents.

Return Specific Fields in Embedded Documents

Use the dot notation to return specific fields in an embedded document.

The following example specifies a projection to return: the _id field, name field, status field, and the foodfield inside the favorites document; the food field remains embedded in the favorites document.

db.users.find(
{ status: "A" },
{ name: 1, status: 1, "favorites.food": 1 }
)

The operation returns the following documents:

{ "_id" : 2, "name" : "bob", "status" : "A", "favorites" : { "food" : "meringue" } }
{ "_id" : 3, "name" : "ahn", "status" : "A", "favorites" : { "food" : "cake" } }
{ "_id" : 6, "name" : "abc", "status" : "A", "favorites" : { "food" : "pizza" } }

Suppress Specific Fields in Embedded Documents

Use dot notation to suppress specific fields of an embedded document using a 0 instead of 1.

The following example specifies a projection to exclude the food field inside the favorites document. All other fields are returned in the matching documents:

db.users.find(
{ status: "A" },
{ "favorites.food": 0 }
)

The operation returns the following document:

{
"_id" : 2,
"name" : "bob",
"age" : 42,
"type" : 1,
"status" : "A",
"favorites" : { "artist" : "Miro" },
"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" },
"finished" : [ 6 ],
"badges" : [ "blue", "red" ],
"points" : [ { "points" : 81, "bonus" : 8 }, { "points" : 55, "bonus" : 20 } ]
}
{
"_id" : 6,
"name" : "abc",
"age" : 43,
"type" : 1,
"status" : "A",
"favorites" : { "artist" : "Picasso" },
"finished" : [ 18, 12 ],
"badges" : [ "black", "blue" ],
"points" : [ { "points" : 78, "bonus" : 8 }, { "points" : 57, "bonus" : 7 } ]
}

Projection on Embedded Documents in an Array

Use dot notation to project specific fields inside documents embedded in an array.

The following example specifies a projection to return the name field, status field, and just the bonus field in the documents in the points array. The _id field is returned by default.

db.users.find( { status: "A" }, { name: 1, status: 1, "points.bonus": 1 } )

The operation returns the following documents:

{ "_id" : 2, "name" : "bob", "status" : "A", "points" : [ { "bonus" : 20 }, { "bonus" : 12 } ] }
{ "_id" : 3, "name" : "ahn", "status" : "A", "points" : [ { "bonus" : 8 }, { "bonus" : 20 } ] }
{ "_id" : 6, "name" : "abc", "status" : "A", "points" : [ { "bonus" : 8 }, { "bonus" : 7 } ] }

Project Specific Array Elements in the Returned Array

For fields that contain arrays, MongoDB provides the following projection operators: $elemMatch$slice, and $.

The following example uses the $slice projection operator to return just the last element in the scores array.

db.users.find( { status: "A" }, { name: 1, status: 1, points: { $slice: -1 } } )

The operation returns the following documents:

{ "_id" : 2, "name" : "bob", "status" : "A", "points" : [ { "points" : 64, "bonus" : 12 } ] }
{ "_id" : 3, "name" : "ahn", "status" : "A", "points" : [ { "points" : 55, "bonus" : 20 } ] }
{ "_id" : 6, "name" : "abc", "status" : "A", "points" : [ { "points" : 57, "bonus" : 7 } ] }

$elemMatch$slice, and $ are the only way to project specific elements to include in the returned array. For instance, you cannot project specific array elements using the array index; e.g. { "ratings.0": 1 } projection will not project the array with the first element.

MongoDB - MongoDB CRUD Operations, Query Documents, Project Fields to Return from Query的更多相关文章

  1. MongoDB - MongoDB CRUD Operations, Insert Documents

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

  2. MongoDB - MongoDB CRUD Operations, Update Documents

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

  3. MongoDB - MongoDB CRUD Operations, Delete Documents

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

  4. 12.Project Fields to Return from Query-官方文档摘录

    1 插入例句 db.inventory.insertMany( [ { item: "journal", status: "A", size: { h: 14, ...

  5. 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 ...

  6. MongoDB - MongoDB CRUD Operations, Query Documents

    Query Method MongoDB provides the db.collection.find() method to read documents from a collection. T ...

  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. word2013中取消句首字母自动大写

    经常使用word的朋友都知道word中一行的首字母会自动大写,这给用户带来方便的同时,也产生了问题,因为有时候我们并不希望每行开头的首字母大写.要取消首字母自动大写可以取消勾选"首句字母大写 ...

  2. C#高性能大容量SOCKET并发(一):IOCP完成端口例子介绍(转)

    原文地址 http://blog.csdn.net/SQLDebug_Fan/article/details/17556353 例子主要包括SocketAsyncEventArgs通讯封装.服务端实现 ...

  3. C# 绘制统计图(柱状图, 折线图, 扇形图)

    统计图形种类繁多, 有柱状图, 折线图, 扇形图等等, 而统计图形的绘制方法也有很多, 有Flash制作的统计图形, 有水晶报表生成统计图形, 有专门制图软件制作, 也有编程语言自己制作的:这里我们用 ...

  4. 推荐大家使用的CSS书写规范及顺序

    @设计达人网 写了这么久的CSS,但大部分前端er都没有按照良好的CSS书写规范来写CSS代码,这样会影响代码的阅读体验,这里我总结一个CSS书写规范.CSS书写顺序供大家参考,这些是参考了国外一些文 ...

  5. C++ CopyFile

    复制文件 关键点 CopyFile The CopyFile function copies an existing file to a new file. The CopyFileEx functi ...

  6. SIP入门(二):建立SIPserver

    在我的上一篇文章中已经介绍怎样通过SIP软电话直接通话,可是假设须要支持很多其它用户互相通话,同一时候基于安全考虑,须要对用户帐户登录进行验证控制,这些情况下就须要建立SIPserver. SIPse ...

  7. JavaScript Design Patterns: Mediator

    The Mediator Design Pattern The Mediator is a behavioral design pattern in which objects, instead of ...

  8. linux 体系结构知识 博客

    http://blog.csdn.net/haiross/article/category/1488205/3

  9. c# 方法参数(传值,传引用,ref,out,params,可选参数,命名参数)

       一.方法参数的类型----值类型和引用类型 当方法传递的参数是值类型时,变量的栈数据会完整地复制到目标参数中即实参和形参中的数据相同但存放在内存的不同位置.所以,在目标方法中对形参所做的更改不会 ...

  10. 1.4.1.Documents,Fields和Schema概述

    Documents,Fields和Schema概述 solr的基本前提是非常简单,你可以给它很多信息,然后可以向它提出问题,获取你想要的问题的信息.所有信息输入的地方就叫做索引或者更新.当你提出问题时 ...