Database Manual / CRUD Operations / Query

Project Fields to Return from Query从查询返回的投影字段

You can use projection to select which document fields to return from a query by using the following methods:您可以使用投影来选择从查询中返回哪些文档字段,方法如下:


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


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 to specify or restrict fields to return.默认情况下,MongoDB中的查询返回匹配文档中的所有字段。为了限制MongoDB发送给应用程序的数据量,您可以包含一个投影文档来指定或限制要返回的字段。

MongoDB Shell

This page provides examples of query operations with projection using the db.collection.find() method in mongosh.本页提供了使用mongoshdb.collection.find()方法进行投影的查询操作示例。

The examples on this page use the inventory collection. Connect to a test database in your MongoDB instance then create the inventory collection:此页面上的示例使用inventory集合。连接到MongoDB实例中的测试数据库,然后创建inventory集合:

Compass

This page provides examples of query operations with projection using MongoDB Compass.本页提供了使用MongoDB Compass进行投影查询操作的示例。

The examples on this page use the inventory collection. Connect to a test database in your MongoDB instance then create the inventory collection:此页面上的示例使用inventory集合。连接到MongoDB实例中的测试数据库,然后创建inventory集合:

C

This page provides examples of query operations with projection using mongoc_collection_find_with_opts.本页提供了使用mongoc_collection_find_with_opts进行投影的查询操作示例。

The examples on this page use the inventory collection. Connect to a test database in your MongoDB instance then create the inventory collection:此页面上的示例使用inventory集合。连接到MongoDB实例中的测试数据库,然后创建inventory集合:

C#

This page provides examples of query operations with projection using the MongoCollection.Find() method in the MongoDB C# Driver.本页提供了使用MongoDB C#驱动程序中的MongoCollection.Find()方法进行投影查询操作的示例。

The examples on this page use the inventory collection. Connect to a test database in your MongoDB instance then create the inventory collection:此页面上的示例使用inventory集合。连接到MongoDB实例中的测试数据库,然后创建inventory集合:

Go

This page provides examples of query operations with projection using the Collection.Find function in the MongoDB Go Driver.本页提供了使用MongoDB Go驱动程序中的Collection.Find函数进行投影查询操作的示例。

The examples on this page use the inventory collection. Connect to a test database in your MongoDB instance then create the inventory collection:此页面上的示例使用inventory集合。连接到MongoDB实例中的测试数据库,然后创建inventory集合:

Java(Async)

This page provides examples of query operations with projection using the com.mongodb.reactivestreams.client.MongoCollection.find method in the MongoDB Java Reactive Streams Driver.本页提供了使用MongoDB Java Reactive Streams驱动程序中的com.mongodb.reactivestreams.client.MongoCollection.find方法进行投影的查询操作示例。

The examples on this page use the inventory collection. Connect to a test database in your MongoDB instance then create the inventory collection:此页面上的示例使用inventory集合。连接到MongoDB实例中的测试数据库,然后创建inventory集合:

Java(Sync)

This page provides examples of query operations with projection using the com.mongodb.client.MongoCollection.find method in the MongoDB Java Synchronous Driver.本页提供了使用MongoDB Java同步驱动程序中的com.mongodb.client.MongoCollection.find方法进行投影查询操作的示例。

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.该驱动程序提供了com.mongodb.client.model.Filters辅助方法,以方便创建筛选器文档。本页上的示例使用这些方法创建筛选文档。

The examples on this page use the inventory collection. Connect to a test database in your MongoDB instance then create the inventory collection:此页面上的示例使用inventory集合。连接到MongoDB实例中的测试数据库,然后创建inventory集合:

Kotlin(Coroutine)

This page provides examples of query operations with projection by using the MongoCollection.find() method in the MongoDB Kotlin Coroutine Driver.本页提供了使用MongoDB Kotlin协程驱动程序中的MongoCollection.find()方法进行投影查询操作的示例。

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.该驱动程序提供了com.mongodb.client.model.Filters辅助方法,以方便创建筛选器文档。本页上的示例使用这些方法创建筛选文档。

The examples on this page use the inventory collection. Connect to a test database in your MongoDB instance then create the inventory collection:此页面上的示例使用inventory集合。连接到MongoDB实例中的测试数据库,然后创建inventory集合:

Motor

This page provides examples of query operations with projection using the motor.motor_asyncio.AsyncIOMotorCollection.find method in the Motor driver.此页面提供了使用Motor驱动程序中的motor.motor_asyncio.AsyncIOMotorCollection.find方法进行投影的查询操作示例。

The examples on this page use the inventory collection. Connect to a test database in your MongoDB instance then create the inventory collection:此页面上的示例使用inventory集合。连接到MongoDB实例中的测试数据库,然后创建inventory集合:

Node.js

This page provides examples of query operations with projection using the Collection.find() method in the MongoDB Node.js Driver.本页提供了使用MongoDB Node.js驱动程序中的Collection.find()方法进行投影的查询操作示例。

The examples on this page use the inventory collection. Connect to a test database in your MongoDB instance then create the inventory collection:此页面上的示例使用inventory集合。连接到MongoDB实例中的测试数据库,然后创建inventory集合:

PHP

This page provides examples of query operations with projection using the MongoDB\\Collection::find() method in the MongoDB PHP Library.本页提供了使用MongoDB PHP库中的MongoDB\\Collection::find()方法进行投影查询操作的示例。

The examples on this page use the inventory collection. Connect to a test database in your MongoDB instance then create the inventory collection:此页面上的示例使用inventory集合。连接到MongoDB实例中的测试数据库,然后创建inventory集合:

Python

This page provides examples of query operations with projection using the pymongo.collection.Collection.find method in the PyMongo Python driver.本页提供了使用PyMongo Python驱动程序中的pymongo.collection.Collection.find方法进行投影查询操作的示例。

The examples on this page use the inventory collection. Connect to a test database in your MongoDB instance then create the inventory collection:此页面上的示例使用inventory集合。连接到MongoDB实例中的测试数据库,然后创建inventory集合:

Ruby

This page provides examples of query operations with projection using the Mongo::Collection#find() method in the MongoDB Ruby Driver.本页提供了使用MongoDB Ruby驱动程序中的Mongo::Collection#find()方法进行投影查询操作的示例。

The examples on this page use the inventory collection. Connect to a test database in your MongoDB instance then create the inventory collection:此页面上的示例使用inventory集合。连接到MongoDB实例中的测试数据库,然后创建inventory集合:

scala

This page provides examples of query operations with projection using the collection.find() method in the MongoDB Scala Driver.本页提供了使用MongoDB Scala驱动程序中的collection.find()方法进行投影的查询操作示例。

The examples on this page use the inventory collection. Connect to a test database in your MongoDB instance then create the inventory collection:此页面上的示例使用inventory集合。连接到MongoDB实例中的测试数据库,然后创建inventory集合:

MongoDB Shell
db.inventory.insertMany( [
{ item: "journal", status: "A", size: { h: 14, w: 21, uom: "cm" }, instock: [ { warehouse: "A", qty: 5 } ] },
{ item: "notebook", status: "A", size: { h: 8.5, w: 11, uom: "in" }, instock: [ { warehouse: "C", qty: 5 } ] },
{ item: "paper", status: "D", size: { h: 8.5, w: 11, uom: "in" }, instock: [ { warehouse: "A", qty: 60 } ] },
{ item: "planner", status: "D", size: { h: 22.85, w: 30, uom: "cm" }, instock: [ { warehouse: "A", qty: 40 } ] },
{ item: "postcard", status: "A", size: { h: 10, w: 15.25, uom: "cm" }, instock: [ { warehouse: "B", qty: 15 }, { warehouse: "C", qty: 35 } ] }
]);
Compass
[
{ "item": "journal", "status": "A", "size": { "h": 14, "w": 21, "uom": "cm" }, "instock": [ { "warehouse": "A", "qty": 5 } ] },
{ "item": "notebook", "status": "A", "size": { "h": 8.5, "w": 11, "uom": "in" }, "instock": [ { "warehouse": "C", "qty": 5 } ] },
{ "item": "paper", "status": "D", "size": { "h": 8.5, "w": 11, "uom": "in" }, "instock": [ { "warehouse": "A", "qty": 60 } ] },
{ "item": "planner", "status": "D", "size": { "h": 22.85, "w": 30, "uom": "cm" }, "instock": [ { "warehouse": "A", "qty": 40 } ] },
{ "item": "postcard", "status": "A", "size": { "h": 10, "w": 15.25, "uom": "cm" }, "instock": [ { "warehouse": "B", "qty": 15 }, { "warehouse": "C", "qty": 35 } ] }
]

For instructions on inserting documents in MongoDB Compass, see Insert Documents.有关在MongoDB Compass中插入文档的说明,请参阅插入文档

C
mongoc_collection_t *collection;
mongoc_bulk_operation_t *bulk;
bson_t *doc;
bool r;
bson_error_t error;
bson_t reply;

collection = mongoc_database_get_collection (db, "inventory");
bulk = mongoc_collection_create_bulk_operation_with_opts (collection, NULL);
doc = BCON_NEW (
"item", BCON_UTF8 ("journal"),
"status", BCON_UTF8 ("A"),
"size", "{",
"h", BCON_DOUBLE (14),
"w", BCON_DOUBLE (21),
"uom", BCON_UTF8 ("cm"),
"}",
"instock", "[",
"{",
"warehouse", BCON_UTF8 ("A"),
"qty", BCON_INT64 (5),
"}",
"]");

r = mongoc_bulk_operation_insert_with_opts (bulk, doc, NULL, &error);
bson_destroy (doc);
if (!r) {
MONGOC_ERROR ("%s\n", error.message);
goto done;
}

doc = BCON_NEW (
"item", BCON_UTF8 ("notebook"),
"status", BCON_UTF8 ("A"),
"size", "{",
"h", BCON_DOUBLE (8.5),
"w", BCON_DOUBLE (11),
"uom", BCON_UTF8 ("in"),
"}",
"instock", "[",
"{",
"warehouse", BCON_UTF8 ("C"),
"qty", BCON_INT64 (5),
"}",
"]");

r = mongoc_bulk_operation_insert_with_opts (bulk, doc, NULL, &error);
bson_destroy (doc);
if (!r) {
MONGOC_ERROR ("%s\n", error.message);
goto done;
}

doc = BCON_NEW (
"item", BCON_UTF8 ("paper"),
"status", BCON_UTF8 ("D"),
"size", "{",
"h", BCON_DOUBLE (8.5),
"w", BCON_DOUBLE (11),
"uom", BCON_UTF8 ("in"),
"}",
"instock", "[",
"{",
"warehouse", BCON_UTF8 ("A"),
"qty", BCON_INT64 (60),
"}",
"]");

r = mongoc_bulk_operation_insert_with_opts (bulk, doc, NULL, &error);
bson_destroy (doc);
if (!r) {
MONGOC_ERROR ("%s\n", error.message);
goto done;
}

doc = BCON_NEW (
"item", BCON_UTF8 ("planner"),
"status", BCON_UTF8 ("D"),
"size", "{",
"h", BCON_DOUBLE (22.85),
"w", BCON_DOUBLE (30),
"uom", BCON_UTF8 ("cm"),
"}",
"instock", "[",
"{",
"warehouse", BCON_UTF8 ("A"),
"qty", BCON_INT64 (40),
"}",
"]");

r = mongoc_bulk_operation_insert_with_opts (bulk, doc, NULL, &error);
bson_destroy (doc);
if (!r) {
MONGOC_ERROR ("%s\n", error.message);
goto done;
}

doc = BCON_NEW (
"item", BCON_UTF8 ("postcard"),
"status", BCON_UTF8 ("A"),
"size", "{",
"h", BCON_DOUBLE (10),
"w", BCON_DOUBLE (15.25),
"uom", BCON_UTF8 ("cm"),
"}",
"instock", "[",
"{",
"warehouse", BCON_UTF8 ("B"),
"qty", BCON_INT64 (15),
"}","{",
"warehouse", BCON_UTF8 ("C"),
"qty", BCON_INT64 (35),
"}",
"]");

r = mongoc_bulk_operation_insert_with_opts (bulk, doc, NULL, &error);
bson_destroy (doc);
if (!r) {
MONGOC_ERROR ("%s\n", error.message);
goto done;
}

/* "reply" is initialized on success or error */
r = (bool) mongoc_bulk_operation_execute (bulk, &reply, &error);
if (!r) {
MONGOC_ERROR ("%s\n", error.message);
}
C#
var documents = new[]
{
new BsonDocument
{
{ "item", "journal" },
{ "status", "A" },
{ "size", new BsonDocument { { "h", 14 }, { "w", 21 }, { "uom", "cm" } } },
{ "instock", new BsonArray
{
new BsonDocument { { "warehouse", "A" }, { "qty", 5 } } }
}
},
new BsonDocument
{
{ "item", "notebook" },
{ "status", "A" },
{ "size", new BsonDocument { { "h", 8.5 }, { "w", 11 }, { "uom", "in" } } },
{ "instock", new BsonArray
{
new BsonDocument { { "warehouse", "C" }, { "qty", 5 } } }
}
},
new BsonDocument
{
{ "item", "paper" },
{ "status", "D" },
{ "size", new BsonDocument { { "h", 8.5 }, { "w", 11 }, { "uom", "in" } } },
{ "instock", new BsonArray
{
new BsonDocument { { "warehouse", "A" }, { "qty", 60 } } }
}
},
new BsonDocument
{
{ "item", "planner" },
{ "status", "D" },
{ "size", new BsonDocument { { "h", 22.85 }, { "w", 30 }, { "uom", "cm" } } },
{ "instock", new BsonArray
{
new BsonDocument { { "warehouse", "A" }, { "qty", 40 } } }
}
},
new BsonDocument
{
{ "item", "postcard" },
{ "status", "A" },
{ "size", new BsonDocument { { "h", 10 }, { "w", 15.25 }, { "uom", "cm" } } },
{ "instock", new BsonArray
{
new BsonDocument { { "warehouse", "B" }, { "qty", 15 } },
new BsonDocument { { "warehouse", "C" }, { "qty", 35 } } }
}
}
};
collection.InsertMany(documents);
Go
docs := []any{
bson.D{
{"item", "journal"},
{"status", "A"},
{"size", bson.D{
{"h", 14},
{"w", 21},
{"uom", "cm"},
}},
{"instock", bson.A{
bson.D{
{"warehouse", "A"},
{"qty", 5},
},
}},
},
bson.D{
{"item", "notebook"},
{"status", "A"},
{"size", bson.D{
{"h", 8.5},
{"w", 11},
{"uom", "in"},
}},
{"instock", bson.A{
bson.D{
{"warehouse", "EC"},
{"qty", 5},
},
}},
},
bson.D{
{"item", "paper"},
{"status", "D"},
{"size", bson.D{
{"h", 8.5},
{"w", 11},
{"uom", "in"},
}},
{"instock", bson.A{
bson.D{
{"warehouse", "A"},
{"qty", 60},
},
}},
},
bson.D{
{"item", "planner"},
{"status", "D"},
{"size", bson.D{
{"h", 22.85},
{"w", 30},
{"uom", "cm"},
}},
{"instock", bson.A{
bson.D{
{"warehouse", "A"},
{"qty", 40},
},
}},
},
bson.D{
{"item", "postcard"},
{"status", "A"},
{"size", bson.D{
{"h", 10},
{"w", 15.25},
{"uom", "cm"},
}},
{"instock", bson.A{
bson.D{
{"warehouse", "B"},
{"qty", 15},
},
bson.D{
{"warehouse", "EC"},
{"qty", 35},
},
}},
},
}

result, err := coll.InsertMany(context.TODO(), docs)
Java(Async)
Publisher<Success> insertManyPublisher = collection.insertMany(asList(
Document.parse("{ item: 'journal', status: 'A', size: { h: 14, w: 21, uom: 'cm' }, instock: [ { warehouse: 'A', qty: 5 }]}"),
Document.parse("{ item: 'notebook', status: 'A', size: { h: 8.5, w: 11, uom: 'in' }, instock: [ { warehouse: 'C', qty: 5}]}"),
Document.parse("{ item: 'paper', status: 'D', size: { h: 8.5, w: 11, uom: 'in' }, instock: [ { warehouse: 'A', qty: 60 }]}"),
Document.parse("{ item: 'planner', status: 'D', size: { h: 22.85, w: 30, uom: 'cm' }, instock: [ { warehouse: 'A', qty: 40}]}"),
Document.parse("{ item: 'postcard', status: 'A', size: { h: 10, w: 15.25, uom: 'cm' }, "
+ "instock: [ { warehouse: 'B', qty: 15 }, { warehouse: 'C', qty: 35 } ] }")
));
Java(Sync)
collection.insertMany(asList(
Document.parse("{ item: 'journal', status: 'A', size: { h: 14, w: 21, uom: 'cm' }, instock: [ { warehouse: 'A', qty: 5 }]}"),
Document.parse("{ item: 'notebook', status: 'A', size: { h: 8.5, w: 11, uom: 'in' }, instock: [ { warehouse: 'C', qty: 5}]}"),
Document.parse("{ item: 'paper', status: 'D', size: { h: 8.5, w: 11, uom: 'in' }, instock: [ { warehouse: 'A', qty: 60 }]}"),
Document.parse("{ item: 'planner', status: 'D', size: { h: 22.85, w: 30, uom: 'cm' }, instock: [ { warehouse: 'A', qty: 40}]}"),
Document.parse("{ item: 'postcard', status: 'A', size: { h: 10, w: 15.25, uom: 'cm' }, "
+ "instock: [ { warehouse: 'B', qty: 15 }, { warehouse: 'C', qty: 35 } ] }")
));
Kotlin(Coroutine)
collection.insertMany(
listOf(
Document("item", "journal")
.append("status", "A")
.append("size", Document("h", 14).append("w", 21).append("uom", "cm"))
.append("instock", listOf(
Document("warehouse", "A").append("qty", 5),
)),
Document("item", "notebook")
.append("status", "A")
.append("size", Document("h", 8.5).append("w", 11).append("uom", "in"))
.append("instock", listOf(
Document("warehouse", "C").append("qty", 5),
)),
Document("item", "paper")
.append("status", "D")
.append("size", Document("h", 8.5).append("w", 11).append("uom", "in"))
.append("instock", listOf(
Document("warehouse", "A").append("qty", 60),
)),
Document("item", "planner")
.append("status", "D")
.append("size", Document("h", 22.85).append("w", 30).append("uom", "cm"))
.append("instock", listOf(
Document("warehouse", "A").append("qty", 40),
)),
Document("item", "postcard")
.append("status", "A")
.append("size", Document("h", 10).append("w", 15.25).append("uom", "cm"))
.append("instock", listOf(
Document("warehouse", "B").append("qty", 15),
Document("warehouse", "C").append("qty", 35)
)),
)
)
Motor
await db.inventory.insert_many(
[
{
"item": "journal",
"status": "A",
"size": {"h": 14, "w": 21, "uom": "cm"},
"instock": [{"warehouse": "A", "qty": 5}],
},
{
"item": "notebook",
"status": "A",
"size": {"h": 8.5, "w": 11, "uom": "in"},
"instock": [{"warehouse": "C", "qty": 5}],
},
{
"item": "paper",
"status": "D",
"size": {"h": 8.5, "w": 11, "uom": "in"},
"instock": [{"warehouse": "A", "qty": 60}],
},
{
"item": "planner",
"status": "D",
"size": {"h": 22.85, "w": 30, "uom": "cm"},
"instock": [{"warehouse": "A", "qty": 40}],
},
{
"item": "postcard",
"status": "A",
"size": {"h": 10, "w": 15.25, "uom": "cm"},
"instock": [{"warehouse": "B", "qty": 15}, {"warehouse": "C", "qty": 35}],
},
]
)
Node.js
await db.collection('inventory').insertMany([
{
item: 'journal',
status: 'A',
size: { h: 14, w: 21, uom: 'cm' },
instock: [{ warehouse: 'A', qty: 5 }]
},
{
item: 'notebook',
status: 'A',
size: { h: 8.5, w: 11, uom: 'in' },
instock: [{ warehouse: 'C', qty: 5 }]
},
{
item: 'paper',
status: 'D',
size: { h: 8.5, w: 11, uom: 'in' },
instock: [{ warehouse: 'A', qty: 60 }]
},
{
item: 'planner',
status: 'D',
size: { h: 22.85, w: 30, uom: 'cm' },
instock: [{ warehouse: 'A', qty: 40 }]
},
{
item: 'postcard',
status: 'A',
size: { h: 10, w: 15.25, uom: 'cm' },
instock: [
{ warehouse: 'B', qty: 15 },
{ warehouse: 'C', qty: 35 }
]
}
]);
PHP
$insertManyResult = $db->inventory->insertMany([
[
'item' => 'journal',
'status' => 'A',
'size' => ['h' => 14, 'w' => 21, 'uom' => 'cm'],
'instock' => [
['warehouse' => 'A', 'qty' => 5],
],
],
[
'item' => 'notebook',
'status' => 'A',
'size' => ['h' => 8.5, 'w' => 11, 'uom' => 'in'],
'instock' => [
['warehouse' => 'C', 'qty' => 5],
],
],
[
'item' => 'paper',
'status' => 'D',
'size' => ['h' => 8.5, 'w' => 11, 'uom' => 'in'],
'instock' => [
['warehouse' => 'A', 'qty' => 60],
],
],
[
'item' => 'planner',
'status' => 'D',
'size' => ['h' => 22.85, 'w' => 30, 'uom' => 'cm'],
'instock' => [
['warehouse' => 'A', 'qty' => 40],
],
],
[
'item' => 'postcard',
'status' => 'A',
'size' => ['h' => 10, 'w' => 15.25, 'uom' => 'cm'],
'instock' => [
['warehouse' => 'B', 'qty' => 15],
['warehouse' => 'C', 'qty' => 35],
],
],
]);
Python
db.inventory.insert_many(
[
{
"item": "journal",
"status": "A",
"size": {"h": 14, "w": 21, "uom": "cm"},
"instock": [{"warehouse": "A", "qty": 5}],
},
{
"item": "notebook",
"status": "A",
"size": {"h": 8.5, "w": 11, "uom": "in"},
"instock": [{"warehouse": "C", "qty": 5}],
},
{
"item": "paper",
"status": "D",
"size": {"h": 8.5, "w": 11, "uom": "in"},
"instock": [{"warehouse": "A", "qty": 60}],
},
{
"item": "planner",
"status": "D",
"size": {"h": 22.85, "w": 30, "uom": "cm"},
"instock": [{"warehouse": "A", "qty": 40}],
},
{
"item": "postcard",
"status": "A",
"size": {"h": 10, "w": 15.25, "uom": "cm"},
"instock": [{"warehouse": "B", "qty": 15}, {"warehouse": "C", "qty": 35}],
},
]
)
Ruby
client[:inventory].insert_many([{ item: 'journal',
status: 'A',
size: { h: 14, w: 21, uom: 'cm' },
instock: [ { warehouse: 'A', qty: 5 }] },
{ item: 'notebook',
status: 'A',
size: { h: 8.5, w: 11, uom: 'in' },
instock: [ { warehouse: 'C', qty: 5 }] },
{ item: 'paper',
status: 'D',
size: { h: 8.5, w: 11, uom: 'in' },
instock: [ { warehouse: 'A', qty: 60 }] },
{ item: 'planner',
status: 'D',
size: { h: 22.85, w: 30, uom: 'cm' },
instock: [ { warehouse: 'A', qty: 40 }] },
{ item: 'postcard',
status: 'A',
size: { h: 10, w: 15.25, uom: 'cm' },
instock: [ { warehouse: 'B', qty: 15 },
{ warehouse: 'C', qty: 35 }] }])
scala
collection.insertMany(Seq(
Document("""{ item: "journal", status: "A", size: { h: 14, w: 21, uom: "cm" }, instock: [ { warehouse: "A", qty: 5 } ] }"""),
Document("""{ item: "notebook", status: "A", size: { h: 8.5, w: 11, uom: "in" }, instock: [ { warehouse: "C", qty: 5 } ] }"""),
Document("""{ item: "paper", status: "D", size: { h: 8.5, w: 11, uom: "in" }, instock: [ { warehouse: "A", qty: 60 } ] }"""),
Document("""{ item: "planner", status: "D", size: { h: 22.85, w: 30, uom: "cm" }, instock: [ { warehouse: "A", qty: 40 } ] }"""),
Document("""{ item: "postcard", status: "A", size: { h: 10, w: 15.25, uom: "cm" },
instock: [ { warehouse: "B", qty: 15 }, { warehouse: "C", qty: 35 } ] }""")

)).execute()

Return All Fields in Matching Documents返回匹配文档中的所有字段

MongoDB Shell

If you do not specify a projection document, the db.collection.find() method returns all fields in the matching documents.如果不指定投影文档,db.collection.find()方法将返回匹配文档中的所有字段。

Compass

If you do not specify a projection document, Compass returns all fields in the matching documents.如果不指定投影文档,Compass将返回匹配文档中的所有字段。

C

If you do not specify a projection filter, the mongoc_collection_find_with_opts() function returns all fields in the matching documents.如果不指定投影筛选器,mongoc_collection_find_with_opts()函数将返回匹配文档中的所有字段。

C#

If you do not specify a projection filter, the MongoCollection.Find() method returns all fields in the matching documents.如果不指定投影筛选器,MongoCollection.Find()方法将返回匹配文档中的所有字段。

Go

If you do not specify a projection filter, the Find() method returns all fields in the matching documents.如果不指定投影筛选器,则Find()方法将返回匹配文档中的所有字段。

Java(Async)

If you do not specify a projection, the com.mongodb.reactivestreams.client.MongoCollection.find method returns all fields in the matching documents.如果不指定投影,则com.mongodb.reactivestreams.client.MongoCollection.find方法将返回匹配文档中的所有字段。

Java(Sync)

If you do not specify a projection, the com.mongodb.client.MongoCollection.find method returns all fields in the matching documents.如果不指定投影,则com.mongodb.client.MongoCollection.find方法将返回匹配文档中的所有字段。

Kotlin(Coroutine)

If you do not specify a projection document, the MongoCollection.find() method returns all fields in the matching documents.如果不指定投影文档,MongoCollection.find()方法将返回匹配文档中的所有字段。

Motor

If you do not specify a projection filter, the find method returns all fields in the matching documents.如果不指定投影筛选器,find方法将返回匹配文档中的所有字段。

Node.js

If you do not specify a projection document, the find() method yields all fields in the matching documents.如果不指定投影文档,find()方法将生成匹配文档中的所有字段。

PHP

If you do not specify a projection document, the find() method returns all fields in the matching documents如果不指定投影文档,find()方法将返回匹配文档中的所有字段

Python

If you do not specify a projection document, the find method returns all fields in the matching documents.如果不指定投影文档,find方法将返回匹配文档中的所有字段。

Ruby

If you do not specify a projection document, the find() method returns all fields in the matching documents.如果不指定投影文档,find()方法将返回匹配文档中的所有字段。

scala

If you do not specify a projection, the collection.find() method returns all fields in the matching documents.如果不指定投影collection.find()方法将返回匹配文档中的所有字段。

The following example returns all fields from all documents in the inventory collection where the status equals "A":以下示例返回status"A"inventory集合中所有文档的所有字段:

MongoDB Shell
db.inventory.find( { status: "A" } )
Compass
  1. Copy the following expression into the Filter field:将以下表达式复制到“筛选器”字段中:

    { status: "A" }
  2. Click Find.
C
mongoc_collection_t *collection;
bson_t *filter;
mongoc_cursor_t *cursor;

collection = mongoc_database_get_collection (db, "inventory");
filter = BCON_NEW ("status", BCON_UTF8 ("A"));
cursor = mongoc_collection_find_with_opts (collection, filter, NULL, NULL);
C#
var filter = Builders<BsonDocument>.Filter.Eq("status", "A");
var result = collection.Find(filter).ToList();
Go
cursor, err := coll.Find(
context.TODO(),
bson.D{{"status", "A"}},
)
Java(Async)
FindPublisher<Document> findPublisher = collection.find(eq("status", "A"));
Java(Sync)
FindIterable<Document> findIterable = collection.find(eq("status", "A"));
Kotlin(Coroutine)
val findFlow = collection
.find(eq("status", "A"))
Motor
cursor = db.inventory.find({"status": "A"})
Node.js
const cursor = db.collection('inventory').find({
status: 'A'
});
PHP
$cursor = $db->inventory->find(['status' => 'A']);
Python
cursor = db.inventory.find({"status": "A"})
Ruby
client[:inventory].find(status: 'A')
scala
var findObservable = collection.find(equal("status", "A"))

The operation corresponds to the following SQL statement:该操作对应于以下SQL语句:

SELECT * from inventory WHERE status = "A"

Return the Specified Fields and the _id Field Only仅返回指定字段和_id字段

A projection can explicitly include several fields by setting the <field> to 1 in the projection document. 通过在投影文档中将<field>设置为1,投影可以明确地包含多个字段。The following operation returns all documents that match the query. In the result set, only the item, status and, by default, the _id fields return in the matching documents.以下操作返回与查询匹配的所有文档。在结果集中,匹配的文档中只返回itemstatus和默认的_id字段。

MongoDB Shell
db.inventory.find( { status: "A" }, { item: 1, status: 1 } )
Compass
  1. Copy the following expression into the Filter field:将以下表达式复制到“筛选器”字段中:

    { status: "A" }
  2. Click Options to open the additional query options.单击“选项”打开其他查询选项。
  3. Copy the following expression into the Project field:将以下表达式复制到“投影”字段中:

    { item: 1, status: 1 }
  4. Click Find.单击“查找”。
C
mongoc_collection_t *collection;
bson_t *filter;
bson_t *opts;
mongoc_cursor_t *cursor;

collection = mongoc_database_get_collection (db, "inventory");
filter = BCON_NEW ("status", BCON_UTF8 ("A"));
opts = BCON_NEW ("projection", "{", "item", BCON_INT64 (1),
"status", BCON_INT64 (1), "}");
cursor = mongoc_collection_find_with_opts (collection, filter, opts, NULL);

Be sure to also clean up any open resources by calling the following methods, as appropriate:请确保根据需要调用以下方法来清理任何开放资源:

C#
var filter = Builders<BsonDocument>.Filter.Eq("status", "A");
var projection = Builders<BsonDocument>.Projection.Include("item").Include("status");
var result = collection.Find<BsonDocument>(filter).Project(projection).ToList();
Go
projection := bson.D{
{"item", 1},
{"status", 1},
}

cursor, err := coll.Find(
context.TODO(),
bson.D{
{"status", "A"},
},
options.Find().SetProjection(projection),
)
Java(Async)
findPublisher = collection.find(eq("status", "A")).projection(include("item", "status"));
Java(Sync)

To specify a projection document, chain the com.mongodb.client.FindIterable.projection method to the find method. 要指定投影文档,请将com.mongodb.client.FindIterable.projection方法链接到find方法。The example uses the com.mongodb.client.model.Projections class to create the projection documents.该示例使用com.mongodb.client.model.Projections类创建投影文档。

findIterable = collection.find(eq("status", "A")).projection(include("item", "status"));
Kotlin(Coroutine)
val findFlow = collection
.find(eq("status", "A")).projection(include("item", "status"))
Motor
cursor = db.inventory.find({"status": "A"}, {"item": 1, "status": 1})
Node.js
const cursor = db
.collection('inventory')
.find({
status: 'A'
})
.project({ item: 1, status: 1 });
PHP
$cursor = $db->inventory->find(
['status' => 'A'],
['projection' => ['item' => 1, 'status' => 1]],
);
Python
cursor = db.inventory.find({"status": "A"}, {"item": 1, "status": 1})
Ruby
client[:inventory].find({ status: 'A' },
projection: { item: 1, status: 1 })
scala
findObservable = collection.find(equal("status", "A")).projection(include("item", "status"))

The operation corresponds to the following SQL statement:该操作对应于以下SQL语句:

SELECT _id, item, status from inventory WHERE status = "A"

Suppress _id Field抑制_id字段

You can remove the _id field from the results by setting it to 0 in the projection, as in the following example:您可以通过在投影中将_id字段设置为0来从结果中删除它,如下例所示:

MongoDB Shell
db.inventory.find( { status: "A" }, { item: 1, status: 1, _id: 0 } )
Compass
  1. Copy the following expression into the Filter field:将以下表达式复制到“筛选器”字段中:

    { status: "A" }
  2. Click Options to open the additional query options.单击“选项”打开其他查询选项。
  3. Copy the following expression into the Project field:将以下表达式复制到“投影”字段中:

    { item: 1, status: 1, _id: 0 }
  4. Click Find.
C
mongoc_collection_t *collection;
bson_t *filter;
bson_t *opts;
mongoc_cursor_t *cursor;

collection = mongoc_database_get_collection (db, "inventory");
filter = BCON_NEW ("status", BCON_UTF8 ("A"));
opts = BCON_NEW ("projection", "{", "item", BCON_INT64 (1),
"status", BCON_INT64 (1),
"_id", BCON_INT64 (0), "}");
cursor = mongoc_collection_find_with_opts (collection, filter, opts, NULL);
C#
var filter = Builders<BsonDocument>.Filter.Eq("status", "A");
var projection = Builders<BsonDocument>.Projection.Include("item").Include("status").Exclude("_id");
var result = collection.Find<BsonDocument>(filter).Project(projection).ToList();
Go
projection := bson.D{
{"item", 1},
{"status", 1},
{"_id", 0},
}

cursor, err := coll.Find(
context.TODO(),
bson.D{
{"status", "A"},
},
options.Find().SetProjection(projection),
)
Java(Async)
findPublisher = collection.find(eq("status", "A"))
.projection(fields(include("item", "status"), excludeId()));
Java(Sync)

To specify a projection document, chain the com.mongodb.client.FindIterable.projection method to the find method. 要指定投影文档,请将com.mongodb.client.FindIterable.projection投影方法链接到find方法。The example uses the com.mongodb.client.model.Projections class to create the projection documents.该示例使用com.mongodb.client.model.Projections类创建投影文档。

findIterable = collection.find(eq("status", "A"))
.projection(fields(include("item", "status"), excludeId()));
Kotlin(Coroutine)
val findFlow = collection
.find(eq("status", "A")).projection(fields(include("item", "status"), excludeId()))
Motor
cursor = db.inventory.find({"status": "A"}, {"item": 1, "status": 1, "_id": 0})
Node.js
const cursor = db
.collection('inventory')
.find({
status: 'A'
})
.project({ item: 1, status: 1, _id: 0 });
PHP
$cursor = $db->inventory->find(
['status' => 'A'],
['projection' => ['item' => 1, 'status' => 1, '_id' => 0]],
);
Python
cursor = db.inventory.find({"status": "A"}, {"item": 1, "status": 1, "_id": 0})
Ruby
client[:inventory].find({ status: 'A' },
projection: { item: 1, status: 1, _id: 0 })
scala
findObservable = collection.find(equal("status", "A"))
.projection(fields(include("item", "status"), excludeId()))

The operation corresponds to the following SQL statement:该操作对应于以下SQL语句:

SELECT item, status from inventory WHERE status = "A"

Note

With the exception of the _id field, you cannot combine inclusion and exclusion statements in projection documents.除了_id字段外,您不能在投影文档中组合包含和排除语句。

Return All But the Excluded Fields返回除排除字段外的所有字段

Instead of listing the fields to return in the matching document, you can use a projection to exclude specific fields. 您可以使用投影来排除特定字段,而不是在匹配文档中列出要返回的字段。The following example which returns all fields except for the status and the instock fields in the matching documents:以下示例返回匹配文档中除statusinstock字段之外的所有字段:

MongoDB Shell
db.inventory.find( { status: "A" }, { status: 0, instock: 0 } )
Compass
  1. Copy the following expression into the Filter field:将以下表达式复制到“筛选器”字段中:

    { status: "A" }
  2. Click Options to open the additional query options.单击“选项”打开其他查询选项。
  3. Copy the following expression into the Project field:将以下表达式复制到“投影”字段中:

    { status: 0, instock: 0 }
  4. Click Find.单击“查找”。
C
mongoc_collection_t *collection;
bson_t *filter;
bson_t *opts;
mongoc_cursor_t *cursor;

collection = mongoc_database_get_collection (db, "inventory");
filter = BCON_NEW ("status", BCON_UTF8 ("A"));
opts = BCON_NEW ("projection", "{", "status", BCON_INT64 (0),
"instock", BCON_INT64 (0), "}");
cursor = mongoc_collection_find_with_opts (collection, filter, opts, NULL);
C#
var filter = Builders<BsonDocument>.Filter.Eq("status", "A");
var projection = Builders<BsonDocument>.Projection.Exclude("status").Exclude("instock");
var result = collection.Find<BsonDocument>(filter).Project(projection).ToList();
Go
projection := bson.D{
{"status", 0},
{"instock", 0},
}

cursor, err := coll.Find(
context.TODO(),
bson.D{
{"status", "A"},
},
options.Find().SetProjection(projection),
)
Java(Async)
findPublisher = collection.find(eq("status", "A")).projection(exclude("item", "status"));
Java(Sync)

To specify a projection document, chain the com.mongodb.client.FindIterable.projection method to the find method. The example uses the com.mongodb.client.model.Projections class to create the projection documents.

findIterable = collection.find(eq("status", "A")).projection(exclude("item", "status"));
Kotlin(Coroutine)
val findFlow = collection
.find(eq("status", "A")).projection(exclude("item", "status"))
Motor
cursor = db.inventory.find({"status": "A"}, {"status": 0, "instock": 0})
Node.js
const cursor = db
.collection('inventory')
.find({
status: 'A'
})
.project({ status: 0, instock: 0 });
PHP
$cursor = $db->inventory->find(
['status' => 'A'],
['projection' => ['status' => 0, 'instock' => 0]],
);
Python
cursor = db.inventory.find({"status": "A"}, {"status": 0, "instock": 0})
Ruby
client[:inventory].find({ status: 'A' },
projection: { status: 0, instock: 0 })
scala
findObservable = collection.find(equal("status", "A")).projection(exclude("item", "status"))

Note

With the exception of the _id field, you cannot combine inclusion and exclusion statements in projection documents.除了_id字段外,您不能在投影文档中组合包含和排除语句。

Return Specific Fields in Embedded Documents返回嵌入式文档中的特定字段

You can return specific fields in an embedded document. Use the dot notation to refer to the embedded field and set to 1 in the projection document.您可以在嵌入式文档中返回特定字段。使用点符号表示嵌入字段,并在投影文档中将其设置为1

The following example returns:以下示例返回:

  • The _id field (returned by default),_id字段(默认返回),
  • The item field,item字段,
  • The status field,status字段,
  • The uom field in the size document.size文档中的uom字段。

The uom field remains embedded in the size document.uom字段仍嵌入在size文档中。

MongoDB Shell
db.inventory.find(
{ status: "A" },
{ item: 1, status: 1, "size.uom": 1 }
)
Compass
  1. Copy the following expression into the Filter field:将以下表达式复制到“筛选器”字段中:

    { status: "A" }
  2. Click Options to open the additional query options.单击“选项”打开其他查询选项。
  3. Copy the following expression into the Project field:将以下表达式复制到“投影”字段中:

    { item: 1, status: 1, "size.uom": 1 }
  4. Click Find.
C
mongoc_collection_t *collection;
bson_t *filter;
bson_t *opts;
mongoc_cursor_t *cursor;

collection = mongoc_database_get_collection (db, "inventory");
filter = BCON_NEW ("status", BCON_UTF8 ("A"));
opts = BCON_NEW ("projection", "{", "item", BCON_INT64 (1),
"status", BCON_INT64 (1),
"size.uom", BCON_INT64 (1), "}");
cursor = mongoc_collection_find_with_opts (collection, filter, opts, NULL);
C#
var filter = Builders<BsonDocument>.Filter.Eq("status", "A");
var projection = Builders<BsonDocument>.Projection.Include("item").Include("status").Include("size.uom");
var result = collection.Find<BsonDocument>(filter).Project(projection).ToList();
Go
projection := bson.D{
{"item", 1},
{"status", 1},
{"size.uom", 1},
}

cursor, err := coll.Find(
context.TODO(),
bson.D{
{"status", "A"},
},
options.Find().SetProjection(projection),
)
Java(Async)
findPublisher = collection.find(eq("status", "A")).projection(include("item", "status", "size.uom"));
Java(Sync)

To specify a projection document, chain the com.mongodb.client.FindIterable.projection method to the find method. The example uses the com.mongodb.client.model.Projections class to create the projection documents.

findIterable = collection.find(eq("status", "A")).projection(include("item", "status", "size.uom"));
Kotlin(Coroutine)
val findFlow = collection
.find(eq("status", "A")).projection(include("item", "status", "size.uom"))
Motor
cursor = db.inventory.find({"status": "A"}, {"item": 1, "status": 1, "size.uom": 1})
Node.js
const cursor = db
.collection('inventory')
.find({
status: 'A'
})
.project({ item: 1, status: 1, 'size.uom': 1 });
PHP
$cursor = $db->inventory->find(
['status' => 'A'],
['projection' => ['item' => 1, 'status' => 1, 'size.uom' => 1]],
);
Python
cursor = db.inventory.find({"status": "A"}, {"item": 1, "status": 1, "size.uom": 1})
Ruby
client[:inventory].find({ status: 'A' },
projection: { 'item' => 1, 'status' => 1, 'size.uom' => 1 })
scala
findObservable = collection.find(equal("status", "A")).projection(include("item", "status", "size.uom"))

You can also specify embedded fields using the nested form. For example, { item: 1, status: 1, size: { uom: 1 } }.您还可以使用嵌套表单指定嵌入字段。例如,{ item: 1, status: 1, size: { uom: 1 } }

Suppress Specific Fields in Embedded Documents抑制嵌入式文档中的特定字段

You can suppress specific fields in an embedded document. Use the dot notation to refer to the embedded field in the projection document and set to 0.您可以抑制嵌入文档中的特定字段。使用点符号表示投影文档中的嵌入字段,并将其设置为0

The following example specifies a projection to exclude the uom field inside the size document. All other fields are returned in the matching documents:以下示例指定了一个投影,以排除size文档中的uom字段。匹配文档中返回所有其他字段:

MongoDB Shell
db.inventory.find(
{ status: "A" },
{ "size.uom": 0 }
)
Compass
  1. Copy the following expression into the Filter field:将以下表达式复制到“筛选器”字段中:

    { status: "A" }
  2. Click Options to open the additional query options.单击“选项”打开其他查询选项。
  3. Copy the following expression into the Project field:将以下表达式复制到“投影”字段中:

    { "size.uom": 0 }
  4. Click Find.
C
mongoc_collection_t *collection;
bson_t *filter;
bson_t *opts;
mongoc_cursor_t *cursor;

collection = mongoc_database_get_collection (db, "inventory");
filter = BCON_NEW ("status", BCON_UTF8 ("A"));
opts = BCON_NEW ("projection", "{", "size.uom", BCON_INT64 (0), "}");
cursor = mongoc_collection_find_with_opts (collection, filter, opts, NULL);
C#
var filter = Builders<BsonDocument>.Filter.Eq("status", "A");
var projection = Builders<BsonDocument>.Projection.Exclude("size.uom");
var result = collection.Find<BsonDocument>(filter).Project(projection).ToList();
Go
projection := bson.D{
{"size.uom", 0},
}

cursor, err := coll.Find(
context.TODO(),
bson.D{
{"status", "A"},
},
options.Find().SetProjection(projection),
)
Java(Async)
findPublisher = collection.find(eq("status", "A")).projection(exclude("size.uom"));
Java(Sync)

To specify a projection document, chain the com.mongodb.client.FindIterable.projection method to the find method. The example uses the com.mongodb.client.model.Projections class to create the projection documents.

findIterable = collection.find(eq("status", "A")).projection(exclude("size.uom"));
Kotlin(Coroutine)
val findFlow = collection
.find(eq("status", "A")).projection(exclude("size.uom"))
Motor
cursor = db.inventory.find({"status": "A"}, {"size.uom": 0})
Node.js
const cursor = db
.collection('inventory')
.find({
status: 'A'
})
.project({ 'size.uom': 0 });
PHP
$cursor = $db->inventory->find(
['status' => 'A'],
['projection' => ['size.uom' => 0]],
);
Python
cursor = db.inventory.find({"status": "A"}, {"size.uom": 0})
Ruby
client[:inventory].find({ status: 'A' },
projection: { 'size.uom' => 0 })
scala
findObservable = collection.find(equal("status", "A")).projection(exclude("size.uom"))

You can also specify embedded fields using the nested form. For example, { size: { uom: 0 } }.您还可以使用嵌套表单指定嵌入字段。例如,{ size: { uom: 0 } }

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 _id field (returned by default),_id字段(默认返回),
  • The item field,item字段,
  • The status field,status字段,
  • The qty field in the documents embedded in the instock array.instock数组中嵌入的文档中的qty字段。
MongoDB Shell
db.inventory.find( { status: "A" }, { item: 1, status: 1, "instock.qty": 1 } )
Compass
  1. Copy the following expression into the Filter field:将以下表达式复制到“筛选器”字段中:

    { status: "A" }
  2. Click Options to open the additional query options.单击“选项”打开其他查询选项。
  3. Copy the following expression into the Project field:将以下表达式复制到“投影”字段中:

    { item: 1, status: 1, "instock.qty": 1 }
  4. Click Find.
C
mongoc_collection_t *collection;
bson_t *filter;
bson_t *opts;
mongoc_cursor_t *cursor;

collection = mongoc_database_get_collection (db, "inventory");
filter = BCON_NEW ("status", BCON_UTF8 ("A"));
opts = BCON_NEW ("projection", "{", "item", BCON_INT64 (1),
"status", BCON_INT64 (1),
"instock.qty", BCON_INT64 (1), "}");
cursor = mongoc_collection_find_with_opts (collection, filter, opts, NULL);
C#
var filter = Builders<BsonDocument>.Filter.Eq("status", "A");
var projection = Builders<BsonDocument>.Projection.Include("item").Include("status").Include("instock.qty");
var result = collection.Find<BsonDocument>(filter).Project(projection).ToList();
Go
projection := bson.D{
{"item", 1},
{"status", 1},
{"instock.qty", 1},
}

cursor, err := coll.Find(
context.TODO(),
bson.D{
{"status", "A"},
},
options.Find().SetProjection(projection),
)
Java(Async)
findPublisher = collection.find(eq("status", "A")).projection(include("item", "status", "instock.qty"));
Java(Sync)

To specify a projection document, chain the com.mongodb.client.FindIterable.projection method to the find method. The example uses the com.mongodb.client.model.Projections class to create the projection documents.

findIterable = collection.find(eq("status", "A")).projection(include("item", "status", "instock.qty"));
Kotlin(Coroutine)
val findFlow = collection
.find(eq("status", "A")).projection(include("item", "status", "instock.qty"))
Motor
cursor = db.inventory.find({"status": "A"}, {"item": 1, "status": 1, "instock.qty": 1})
Node.js
const cursor = db
.collection('inventory')
.find({
status: 'A'
})
.project({ item: 1, status: 1, 'instock.qty': 1 });
PHP
$cursor = $db->inventory->find(
['status' => 'A'],
['projection' => ['item' => 1, 'status' => 1, 'instock.qty' => 1]],
);
Python
cursor = db.inventory.find({"status": "A"}, {"item": 1, "status": 1, "instock.qty": 1})
Ruby
client[:inventory].find({ status: 'A' },
projection: {'item' => 1, 'status' => 1, 'instock.qty' => 1 })
scala
findObservable = collection.find(equal("status", "A")).projection(include("item", "status", "instock.qty"))

Project Specific Array Elements in the Returned Array投影返回数组中的特定数组元素

For fields that contain arrays, MongoDB provides the following projection operators for manipulating arrays: $elemMatch, $slice, and $.对于包含数组的字段,MongoDB提供了以下用于操纵数组的投影运算符:$elemMatch$slice$

The following example uses the $slice projection operator to return the last element in the instock array:以下示例使用$slice投影运算符返回instock数组中的最后一个元素:

MongoDB Shell
db.inventory.find( { status: "A" }, { item: 1, status: 1, instock: { $slice: -1 } } )
Compass
  1. Copy the following expression into the Filter field:将以下表达式复制到“筛选器”字段中:

    { status: "A" }
  2. Click Options to open the additional query options.单击“选项”打开其他查询选项。
  3. Copy the following expression into the Project field:将以下表达式复制到“投影”字段中:

    { item: 1, status: 1, instock: { $slice: -1 } }
  4. Click Find.单击“查找”。
C
mongoc_collection_t *collection;
bson_t *filter;
bson_t *opts;
mongoc_cursor_t *cursor;

collection = mongoc_database_get_collection (db, "inventory");
filter = BCON_NEW ("status", BCON_UTF8 ("A"));
opts = BCON_NEW ("projection", "{", "item", BCON_INT64 (1),
"status", BCON_INT64 (1),
"instock", "{",
"$slice", BCON_INT64 (-1),
"}", "}");
cursor = mongoc_collection_find_with_opts (collection, filter, opts, NULL);
C#
var filter = Builders<BsonDocument>.Filter.Eq("status", "A");
var projection = Builders<BsonDocument>.Projection.Include("item").Include("status").Slice("instock", -1);
var result = collection.Find<BsonDocument>(filter).Project(projection).ToList();
Go
projection := bson.D{
{"item", 1},
{"status", 1},
{"instock", bson.D{
{"$slice", -1},
}},
}

cursor, err := coll.Find(
context.TODO(),
bson.D{
{"status", "A"},
},
options.Find().SetProjection(projection),
)
Java(Async)
findPublisher = collection.find(eq("status", "A"))
.projection(fields(include("item", "status"), slice("instock", -1)));
Java(Sync)

To specify a projection document, chain the com.mongodb.client.FindIterable.projection method to the find method. The example uses the com.mongodb.client.model.Projections class to create the projection documents.

findIterable = collection.find(eq("status", "A"))
.projection(fields(include("item", "status"), slice("instock", -1)));
Kotlin(Coroutine)

To specify a projection document, chain the FindFlow.projection() method to the find() method. The example uses the com.mongodb.client.model.Projections class to create the projection documents.

val findFlow = collection
.find(eq("status", "A"))
.projection(fields(include("item", "status"), slice("instock", -1)))
Motor
cursor = db.inventory.find(
{"status": "A"}, {"item": 1, "status": 1, "instock": {"$slice": -1}}
)
Node.js
const cursor = db
.collection('inventory')
.find({
status: 'A'
})
.project({ item: 1, status: 1, instock: { $slice: -1 } });
PHP
$cursor = $db->inventory->find(
['status' => 'A'],
['projection' => ['item' => 1, 'status' => 1, 'instock' => ['$slice' => -1]]],
);
Python
cursor = db.inventory.find(
{"status": "A"}, {"item": 1, "status": 1, "instock": {"$slice": -1}}
)
Ruby
client[:inventory].find({ status: 'A' },
projection: {'item' => 1,
'status' => 1,
'instock' => { '$slice' => -1 } })
scala
findObservable = collection.find(equal("status", "A"))
.projection(fields(include("item", "status"), slice("instock", -1)))

$elemMatch, $slice, and $ are the only operators that you can use to project specific elements to include in the returned array. $elemMatch$slice$是唯一可用于投影特定元素以包含在返回数组中的运算符。For instance, you cannot project specific array elements using the array index; e.g. { "instock.0": 1 } projection does not project the array with the first element.例如,您不能使用数组索引投影特定的数组元素;例如,{ "instock.0": 1 }投影不会投影具有第一个元素的数组。

Project Fields with Aggregation Expressions投影使用聚合表达式的字段

You can specify aggregation expressions in a query projection. Aggregation expressions let you project new fields and modify the values of existing fields.您可以在查询投影中指定聚合表达式。聚合表达式允许您投影新字段并修改现有字段的值。

For example, the following operation uses aggregation expressions to override the value of the status field, and project new fields area and reportNumber.例如,以下操作使用聚合表达式覆盖状态字段的值,并投影新字段areareportNumber

Note

The following example uses MongoDB Shell syntax. For driver examples of projection with aggregation, see your driver documentation.以下示例使用MongoDB Shell语法。有关聚合投影的驱动程序示例,请参阅驱动程序文档

db.inventory.find(
{ },
{
_id: 0,
item: 1,
status: {
$switch: {
branches: [
{
case: { $eq: [ "$status", "A" ] },
then: "Available"
},
{
case: { $eq: [ "$status", "D" ] },
then: "Discontinued"
},
],
default: "No status found"
}
},
area: {
$concat: [
{ $toString: { $multiply: [ "$size.h", "$size.w" ] } },
" ",
"$size.uom"
]
},
reportNumber: { $literal: 1 }
}
)
[
{
item: 'journal',
status: 'Available',
area: '294 cm',
reportNumber: 1
},
{
item: 'planner',
status: 'Discontinued',
area: '685.5 cm',
reportNumber: 1
},
{
item: 'notebook',
status: 'Available',
area: '93.5 in',
reportNumber: 1
},
{
item: 'paper',
status: 'Discontinued',
area: '93.5 in',
reportNumber: 1
},
{
item: 'postcard',
status: 'Available',
area: '152.5 cm',
reportNumber: 1
}
]

Project Fields to Return from a Query with MongoDB Atlas投影MongoDB Atlas查询返回的字段

The example in this section uses the sample movies dataset. To learn how to load the sample dataset into your MongoDB Atlas deployment, see Load Sample Data.本节中的示例使用示例电影数据集。要了解如何将示例数据集加载到MongoDB Atlas部署中,请参阅加载示例数据

To project fields to return from a query in MongoDB Atlas, follow these steps:要在MongoDB Atlas中投影要从查询返回的字段,请执行以下步骤:

1

In the MongoDB Atlas UI, go to the Clusters page for your project.在MongoDB Atlas UI中,转到投影的“集群”页面。

Warning

Navigation Improvements In Progress导航改进正在进行中

We're currently rolling out a new and improved navigation experience. If the following steps don't match your view in the Atlas UI, see the preview Atlas documentation.我们目前正在推出一种新的、改进的导航体验。如果以下步骤与Atlas UI中的视图不匹配,请参阅Atlas预览文档

  1. If it's not already displayed, select the organization that contains your desired project from the Organizations menu in the navigation bar.如果尚未显示,请从导航栏的“组织”菜单中选择包含所需投影的组织。
  2. If it's not already displayed, select your project from the Projects menu in the navigation bar.如果尚未显示,请从导航栏中的“投影”菜单中选择您的投影。
  3. If it's not already displayed, click Clusters in the sidebar.如果尚未显示,请单击侧栏中的“集群”。

    The Clusters page displays.将显示“群集”页面。

2

Navigate to the collection导航到集合

  1. For the cluster that contains the sample data, click Browse Collections.对于包含示例数据的集群,单击“浏览集合”。
  2. In the left navigation pane, select the sample_mflix database.在左侧导航窗格中,选择sample_mflix数据库。
  3. Select the movies collection.选择movies集合。
3

Specify the Filter field指定筛选器字段

  1. Click More Options on the right side of the Filter field.单击“筛选器”字段右侧的“更多选项”。
  2. Specify the query filter.指定查询筛选器。

    Specify the query filter document in the Filter field. A query filter document uses query operators to specify search conditions.在“筛选器”字段中指定查询筛选器文档。查询筛选器文档使用查询运算符指定搜索条件。

    Copy the following query filter document into the Filter search bar:将以下查询筛选器文档复制到“筛选器”搜索栏中:

    { year: 1924 }
4

Specify the fields to project指定要投影的字段

Specify the field(s) to return in the query results.指定要在查询结果中返回的字段。

Copy the following project document into the Project bar:将以下投影文档复制到“投影”栏中:

{ title: 1, plot: 1 }
5

Click Apply单击“应用”

This query filter returns the following fields for all documents in the sample_mflix.movies collection where the year field matches 1924:此查询筛选器为sample_mflix.movies集合中的所有文档返回以下字段,其中year字段与1924匹配:

  • _id
  • title
  • plot

MongoDB Atlas returns the _id field by default. To omit the _id field, copy the following project document into the Project bar and click Apply:MongoDB Atlas默认返回_id字段。要省略_id字段,请将以下投影文档复制到投影栏中,然后单击应用:

{ title: 1, plot: 1, _id: 0 }

Additional Considerations其他注意事项

  • When you use a $project aggregation stage it should typically be the last stage in your pipeline, used to specify which fields to return to the client.当您使用$project聚合阶段时,它通常应该是管道中的最后一个阶段,用于指定要返回给客户端的字段。

    Using a $project stage at the beginning or middle of a pipeline to reduce the number of fields passed to subsequent pipeline stages is unlikely to improve performance, because the database performs this optimization automatically.在管道的开始或中间使用$project阶段来减少传递给后续管道阶段的字段数量不太可能提高性能,因为数据库会自动执行此优化。

  • MongoDB enforces additional restrictions with regards to projections. See Projection Restrictions for details.MongoDB对预测实施了额外的限制。有关详细信息,请参阅投影限制