Project Fields to Return from Query要从查询返回的项目字段

This page provides examples in:本页提供了以下示例:

By default, queries in MongoDB return all fields in matching documents. 默认情况下,MongoDB中的查询返回匹配文档中的所有字段。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发送给应用程序的数据量,可以包括一个投影文档来指定或限制要返回的字段。

This page provides examples of query operations with projection using the db.collection.find() method in the mongo shell. 本页提供了使用mongo shell中的db.collection.find()方法进行投影的查询操作示例。The examples on this page use the inventory collection. 本页上的示例使用inventory集合。To populate the inventory collection, run the following:要填充inventory集合,请运行以下操作:

This page provides examples of query operations with projection using MongoDB Compass. 本页提供了使用MongoDB Compass进行投影的查询操作示例。The examples on this page use the inventory collection. 本页上的示例使用inventory集合。Populate the inventory collection with the following documents:使用以下文档填充inventory集合:

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. 本页上的示例使用inventory集合。To populate the inventory collection, run the following:要填充inventory集合,请运行以下操作:

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. 驱动程序提供com.mongodb.client.model.Filters帮助程序方法,以方便创建筛选文档。The examples on this page use these methods to create the filter documents.本页上的示例使用这些方法创建筛选文档。

The examples on this page use the inventory collection. 本页上的示例使用inventory集合。To populate the inventory collection, run the following:要填充inventory集合,请运行以下操作:

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. 本页上的示例使用inventory集合。To populate the inventory collection, run the following:要填充inventory集合,请运行以下操作:

This page provides examples of query operations with projection using the MongoDB\Collection::find() method in the MongoDB PHP Library. The examples on this page use the inventory collection. 本页上的示例使用inventory集合。To populate the inventory collection, run the following:要填充inventory集合,请运行以下操作:

This page provides examples of query operations with projection using the motor.motor_asyncio.AsyncIOMotorCollection.find() method in the Motor driver. The examples on this page use the inventory collection. 本页上的示例使用inventory集合。To populate the inventory collection, run the following:要填充inventory集合,请运行以下操作:

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反应流驱动程序中的com.mongodb.reactivestreams.client.MongoCollection.findcom.mongodb.reactivestreams.client.MongoCollection.find方法进行投影的查询操作示例。

The examples on this page use the inventory collection. 本页上的示例使用inventory集合。To populate the inventory collection, run the following:要填充inventory集合,请运行以下操作:

This page provides examples of query operations with projection using the MongoCollection.Find() method in the MongoDB C# Driver. The examples on this page use the inventory collection. 本页上的示例使用inventory集合。To populate the inventory collection, run the following:要填充inventory集合,请运行以下操作:

This page provides examples of query operations with projection using the MongoDB::Collection::find() method in the MongoDB Perl Driver. The examples on this page use the inventory collection. 本页上的示例使用inventory集合。To populate the inventory collection, run the following:要填充inventory集合,请运行以下操作:

This page provides examples of query operations with projection using the Mongo::Collection#find() method in the MongoDB Ruby Driver. The examples on this page use the inventory collection. 本页上的示例使用inventory集合。To populate the inventory collection, run the following:要填充inventory集合,请运行以下操作:

This page provides examples of query operations with projection using the collection.find() method in the MongoDB Scala Driver. The examples on this page use the inventory collection. 本页上的示例使用inventory集合。To populate the inventory collection, run the following:要填充inventory集合,请运行以下操作:

This page provides examples of query operations with projection using the Collection.Find function in the MongoDB Go Driver. The examples on this page use the inventory collection. 本页上的示例使用inventory集合。To populate the inventory collection, run the following:要填充inventory集合,请运行以下操作:

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

You can run the operation in the web shell below:您可以在下面的web shell中运行该操作:

[
  { 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中插入文档的说明,请参阅插入文档

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}]}])
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 } ] }")
));
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 }
    ]
  }
]);
$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],
        ],
    ],
]);
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}]}])
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 } ] }")
));
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);
$db->coll("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 }
            ]
        }
    ]
);
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 }] }])
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()
docs := []interface{}{
	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.Background(), docs)

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

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

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

If you do not specify a projection document, the find() method returns all fields in the matching documents.

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方法将返回匹配文档中的所有字段。

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

If you do not specify a projection document, the find() method returns all fields in the matching documents.

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方法将返回匹配文档中的所有字段。

If you do not specify a projection filter, the MongoCollection.Find() method returns all fields in the matching documents.

If you do not specify a projection document, the find() method returns all fields in the matching documents.

If you do not specify a projection document, the find() method returns all fields in the matching documents.

If you do not specify a projection, the collection.find() method returns all fields in the matching documents.

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

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

    { status: "A" }
  2. Click Find.点击“查找”。
cursor = db.inventory.find({"status": "A"})
FindIterable<Document> findIterable = collection.find(eq("status", "A"));
const cursor = db.collection('inventory').find({
  status: 'A'
});
$cursor = $db->inventory->find(['status' => 'A']);
cursor = db.inventory.find({"status": "A"})
FindPublisher<Document> findPublisher = collection.find(eq("status", "A"));
var filter = Builders<BsonDocument>.Filter.Eq("status", "A");
var result = collection.Find(filter).ToList();
$cursor = $db->coll("inventory")->find( { status => "A" } );
client[:inventory].find(status: 'A')
var findObservable = collection.find(equal("status", "A"))
cursor, err := coll.Find(
	context.Background(),
	bson.D{{"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字段。

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

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

    { item: 1, status: 1 }
  4. Click Find.点击“查找”。
cursor = db.inventory.find(
    {"status": "A"}, {"item": 1, "status": 1})

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"));
const cursor = db
  .collection('inventory')
  .find({
    status: 'A'
  })
  .project({ item: 1, status: 1 });
$cursor = $db->inventory->find(
    ['status' => 'A'],
    ['projection' => ['item' => 1, 'status' => 1]]
);
cursor = db.inventory.find(
    {"status": "A"}, {"item": 1, "status": 1})
findPublisher = collection.find(eq("status", "A")).projection(include("item", "status"));
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();
$cursor = $db->coll("inventory")->find(
    { status => "A" }, { projection => { item => 1, status => 1 } }
);
client[:inventory].find({ status: 'A' },
                       projection: { item: 1, status: 1 })
findObservable = collection.find(equal("status", "A")).projection(include("item", "status"))
projection := bson.D{
	{"item", 1},
	{"status", 1},
}

cursor, err := coll.Find(
	context.Background(),
	bson.D{
		{"status", "A"},
	},
	options.Find().SetProjection(projection),
)

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,可以从结果中删除该字段,如下例所示:

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

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

    { item: 1, status: 1, _id: 0 }
  4. Click Find.点击“查找”。
cursor = db.inventory.find(
    {"status": "A"}, {"item": 1, "status": 1, "_id": 0})

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()));
const cursor = db
  .collection('inventory')
  .find({
    status: 'A'
  })
  .project({ item: 1, status: 1, _id: 0 });
$cursor = $db->inventory->find(
    ['status' => 'A'],
    ['projection' => ['item' => 1, 'status' => 1, '_id' => 0]]
);
cursor = db.inventory.find(
    {"status": "A"}, {"item": 1, "status": 1, "_id": 0})
findPublisher = collection.find(eq("status", "A"))
        .projection(fields(include("item", "status"), excludeId()));
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();
$cursor = $db->coll("inventory")->find(
    { status => "A" }, { projection => { item => 1, status => 1, "_id" => 0 } }
);
client[:inventory].find({ status: 'A' },
                        projection: { item: 1, status: 1, _id: 0 })
findObservable = collection.find(equal("status", "A"))
  .projection(fields(include("item", "status"), excludeId()))
projection := bson.D{
	{"item", 1},
	{"status", 1},
	{"_id", 0},
}

cursor, err := coll.Find(
	context.Background(),
	bson.D{
		{"status", "A"},
	},
	options.Find().SetProjection(projection),
)

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字段外的所有字段:

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

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

    { status: 0, instock: 0 }
  4. Click Find.点击“查找”。
cursor = db.inventory.find(
    {"status": "A"}, {"status": 0, "instock": 0})

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(exclude("item", "status"));
const cursor = db
  .collection('inventory')
  .find({
    status: 'A'
  })
  .project({ status: 0, instock: 0 });
$cursor = $db->inventory->find(
    ['status' => 'A'],
    ['projection' => ['status' => 0, 'instock' => 0]]
);
cursor = db.inventory.find(
    {"status": "A"}, {"status": 0, "instock": 0})
findPublisher = collection.find(eq("status", "A")).projection(exclude("item", "status"));
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();
$cursor = $db->coll("inventory")->find(
    { status => "A" }, { projection => { status => 0, instock => 0 } }
);
client[:inventory].find({ status: 'A' },
                        projection: { status: 0, instock: 0 })
findObservable = collection.find(equal("status", "A")).projection(exclude("item", "status"))
projection := bson.D{
	{"status", 0},
	{"instock", 0},
}

cursor, err := coll.Find(
	context.Background(),
	bson.D{
		{"status", "A"},
	},
	options.Find().SetProjection(projection),
)

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 uom field remains embedded in the size document.uom字段仍嵌入在size文档中。

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

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

    { item: 1, status: 1, "size.uom": 1 }
  4. Click Find.点击“查找”。
cursor = db.inventory.find(
    {"status": "A"}, {"item": 1, "status": 1, "size.uom": 1})

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", "size.uom"));
const cursor = db
  .collection('inventory')
  .find({
    status: 'A'
  })
  .project({ item: 1, status: 1, 'size.uom': 1 });
$cursor = $db->inventory->find(
    ['status' => 'A'],
    ['projection' => ['item' => 1, 'status' => 1, 'size.uom' => 1]]
);
cursor = db.inventory.find(
    {"status": "A"}, {"item": 1, "status": 1, "size.uom": 1})
findPublisher = collection.find(eq("status", "A")).projection(include("item", "status", "size.uom"));
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();
$cursor = $db->coll("inventory")->find(
    { status => "A" }, { projection => { item => 1, status => 1, "size.uom" => 1 } }
);
client[:inventory].find({ status: 'A' },
                        projection: { 'item' => 1, 'status' => 1, 'size.uom' => 1 })
findObservable = collection.find(equal("status", "A")).projection(include("item", "status", "size.uom"))
projection := bson.D{
	{"item", 1},
	{"status", 1},
	{"size.uom", 1},
}

cursor, err := coll.Find(
	context.Background(),
	bson.D{
		{"status", "A"},
	},
	options.Find().SetProjection(projection),
)

Starting in MongoDB 4.4, you can also specify embedded fields using the nested form, e.g. { item: 1, status: 1, size: { uom: 1 } }.从MongoDB 4.4开始,还可以使用嵌套形式指定嵌入字段,例如{ 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. 以下示例指定一个投影,以排除size文档中的uom字段。All other fields are returned in the matching documents:所有其他字段将在匹配文档中返回:

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

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

    { "size.uom": 0 }
  4. Click Find.点击“查找”。
cursor = db.inventory.find({"status": "A"}, {"size.uom": 0})

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(exclude("size.uom"));
const cursor = db
  .collection('inventory')
  .find({
    status: 'A'
  })
  .project({ 'size.uom': 0 });
$cursor = $db->inventory->find(
    ['status' => 'A'],
    ['projection' => ['size.uom' => 0]]
);
cursor = db.inventory.find({"status": "A"}, {"size.uom": 0})
findPublisher = collection.find(eq("status", "A")).projection(exclude("size.uom"));
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();
$cursor = $db->coll("inventory")->find(
    { status => "A" }, { projection => { "size.uom" => 0 } }
);
client[:inventory].find({ status: 'A' },
                        projection: { 'size.uom' => 0 })
findObservable = collection.find(equal("status", "A")).projection(exclude("size.uom"))
projection := bson.D{
	{"size.uom", 0},
}

cursor, err := coll.Find(
	context.Background(),
	bson.D{
		{"status", "A"},
	},
	options.Find().SetProjection(projection),
)

Starting in MongoDB 4.4, you can also specify embedded fields using the nested form, e.g. { size: { uom: 0 } }.从MongoDB 4.4开始,还可以使用嵌套形式指定嵌入字段,例如{ item: 1, status: 1, size: { uom: 1 } }

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:以下示例指定要返回的投影:

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

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

    { item: 1, status: 1, "instock.qty": 1 }
  4. Click Find.点击“查找”。
cursor = db.inventory.find(
    {"status": "A"}, {"item": 1, "status": 1, "instock.qty": 1})

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", "instock.qty"));
const cursor = db
  .collection('inventory')
  .find({
    status: 'A'
  })
  .project({ item: 1, status: 1, 'instock.qty': 1 });
$cursor = $db->inventory->find(
    ['status' => 'A'],
    ['projection' => ['item' => 1, 'status' => 1, 'instock.qty' => 1]]
);
cursor = db.inventory.find(
    {"status": "A"}, {"item": 1, "status": 1, "instock.qty": 1})
findPublisher = collection.find(eq("status", "A")).projection(include("item", "status", "instock.qty"));
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();
$cursor = $db->coll("inventory")->find( { status => "A" },
    { projection => { item => 1, status => 1, "instock.qty" => 1 } } );
client[:inventory].find({ status: 'A' },
                        projection: {'item' => 1, 'status' => 1, 'instock.qty' => 1 })
findObservable = collection.find(equal("status", "A")).projection(include("item", "status", "instock.qty"))
projection := bson.D{
	{"item", 1},
	{"status", 1},
	{"instock.qty", 1},
}

cursor, err := coll.Find(
	context.Background(),
	bson.D{
		{"status", "A"},
	},
	options.Find().SetProjection(projection),
)

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数组中的最后一个元素:

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

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

    { item: 1, status: 1, instock: { $slice: -1 } }
  4. Click Find.点击“查找”。
cursor = db.inventory.find(
    {"status": "A"},
    {"item": 1, "status": 1, "instock": {"$slice": -1}})

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"), slice("instock", -1)));
const cursor = db
  .collection('inventory')
  .find({
    status: 'A'
  })
  .project({ item: 1, status: 1, instock: { $slice: -1 } });
$cursor = $db->inventory->find(
    ['status' => 'A'],
    ['projection' => ['item' => 1, 'status' => 1, 'instock' => ['$slice' => -1]]]
);
cursor = db.inventory.find(
    {"status": "A"},
    {"item": 1, "status": 1, "instock": {"$slice": -1}})
findPublisher = collection.find(eq("status", "A"))
        .projection(fields(include("item", "status"), slice("instock", -1)));
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();
$cursor = $db->coll("inventory")->find(
    { status => "A" },
    { projection => { item => 1, status => 1, instock => { '$slice' => -1 } } }
);
client[:inventory].find({ status: 'A' },
                        projection: {'item' => 1,
                                     'status' => 1,
                                     'instock' => { '$slice' => -1 } })
findObservable = collection.find(equal("status", "A"))
  .projection(fields(include("item", "status"), slice("instock", -1)))
projection := bson.D{
	{"item", 1},
	{"status", 1},
	{"instock", bson.D{
		{"$slice", -1},
	}},
}

cursor, err := coll.Find(
	context.Background(),
	bson.D{
		{"status", "A"},
	},
	options.Find().SetProjection(projection),
)

$elemMatch, $slice, and $ are the only way 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 will not project the array with the first element.例如,不能使用数组索引投影特定数组元素;例如,{ "instock.0": 1 }投影将不会投影具有第一个元素的数组。

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数组中的最后一个元素:

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

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

    { item: 1, status: 1, instock: { $slice: -1 } }
  4. Click Find.点击“查找”。
cursor = db.inventory.find(
    {"status": "A"},
    {"item": 1, "status": 1, "instock": {"$slice": -1}})

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"), slice("instock", -1)));
const cursor = db
  .collection('inventory')
  .find({
    status: 'A'
  })
  .project({ item: 1, status: 1, instock: { $slice: -1 } });
$cursor = $db->inventory->find(
    ['status' => 'A'],
    ['projection' => ['item' => 1, 'status' => 1, 'instock' => ['$slice' => -1]]]
);
cursor = db.inventory.find(
    {"status": "A"},
    {"item": 1, "status": 1, "instock": {"$slice": -1}})
findPublisher = collection.find(eq("status", "A"))
        .projection(fields(include("item", "status"), slice("instock", -1)));
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();
$cursor = $db->coll("inventory")->find(
    { status => "A" },
    { projection => { item => 1, status => 1, instock => { '$slice' => -1 } } }
);
client[:inventory].find({ status: 'A' },
                        projection: {'item' => 1,
                                     'status' => 1,
                                     'instock' => { '$slice' => -1 } })
findObservable = collection.find(equal("status", "A"))
  .projection(fields(include("item", "status"), slice("instock", -1)))
projection := bson.D{
	{"item", 1},
	{"status", 1},
	{"instock", bson.D{
		{"$slice", -1},
	}},
}

cursor, err := coll.Find(
	context.Background(),
	bson.D{
		{"status", "A"},
	},
	options.Find().SetProjection(projection),
)

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

The following example uses the $slice projection operator to return the last element in the instock array:

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

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

    { item: 1, status: 1, instock: { $slice: -1 } }
  4. Click Find.点击“查找”。
cursor = db.inventory.find(
    {"status": "A"},
    {"item": 1, "status": 1, "instock": {"$slice": -1}})

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"), slice("instock", -1)));
const cursor = db
  .collection('inventory')
  .find({
    status: 'A'
  })
  .project({ item: 1, status: 1, instock: { $slice: -1 } });
$cursor = $db->inventory->find(
    ['status' => 'A'],
    ['projection' => ['item' => 1, 'status' => 1, 'instock' => ['$slice' => -1]]]
);
cursor = db.inventory.find(
    {"status": "A"},
    {"item": 1, "status": 1, "instock": {"$slice": -1}})
findPublisher = collection.find(eq("status", "A"))
        .projection(fields(include("item", "status"), slice("instock", -1)));
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();
$cursor = $db->coll("inventory")->find(
    { status => "A" },
    { projection => { item => 1, status => 1, instock => { '$slice' => -1 } } }
);
client[:inventory].find({ status: 'A' },
                        projection: {'item' => 1,
                                     'status' => 1,
                                     'instock' => { '$slice' => -1 } })
findObservable = collection.find(equal("status", "A"))
  .projection(fields(include("item", "status"), slice("instock", -1)))
projection := bson.D{
	{"item", 1},
	{"status", 1},
	{"instock", bson.D{
		{"$slice", -1},
	}},
}

cursor, err := coll.Find(
	context.Background(),
	bson.D{
		{"status", "A"},
	},
	options.Find().SetProjection(projection),
)

$elemMatch, $slice, and $ are the only way 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 will not project the array with the first element.例如,不能使用数组索引投影特定数组元素;例如,{ "instock.0": 1 }投影将不会投影具有第一个元素的数组。

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数组中的最后一个元素:

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

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

    { item: 1, status: 1, instock: { $slice: -1 } }
  4. Click Find.点击“查找”。
cursor = db.inventory.find(
    {"status": "A"},
    {"item": 1, "status": 1, "instock": {"$slice": -1}})

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"), slice("instock", -1)));
const cursor = db
  .collection('inventory')
  .find({
    status: 'A'
  })
  .project({ item: 1, status: 1, instock: { $slice: -1 } });
$cursor = $db->inventory->find(
    ['status' => 'A'],
    ['projection' => ['item' => 1, 'status' => 1, 'instock' => ['$slice' => -1]]]
);
cursor = db.inventory.find(
    {"status": "A"},
    {"item": 1, "status": 1, "instock": {"$slice": -1}})
findPublisher = collection.find(eq("status", "A"))
        .projection(fields(include("item", "status"), slice("instock", -1)));
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();
$cursor = $db->coll("inventory")->find(
    { status => "A" },
    { projection => { item => 1, status => 1, instock => { '$slice' => -1 } } }
);
client[:inventory].find({ status: 'A' },
                        projection: {'item' => 1,
                                     'status' => 1,
                                     'instock' => { '$slice' => -1 } })
findObservable = collection.find(equal("status", "A"))
  .projection(fields(include("item", "status"), slice("instock", -1)))
projection := bson.D{
	{"item", 1},
	{"status", 1},
	{"instock", bson.D{
		{"$slice", -1},
	}},
}

cursor, err := coll.Find(
	context.Background(),
	bson.D{
		{"status", "A"},
	},
	options.Find().SetProjection(projection),
)

$elemMatch, $slice, and $ are the only way 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. include("instock.0") projection will not project the array with the first element.例如,不能使用数组索引投影特定数组元素;例如,include("instock.0")投影将不会投影具有第一个元素的数组。

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数组中的最后一个元素:

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

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

    { item: 1, status: 1, instock: { $slice: -1 } }
  4. Click Find.点击“查找”。
cursor = db.inventory.find(
    {"status": "A"},
    {"item": 1, "status": 1, "instock": {"$slice": -1}})

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"), slice("instock", -1)));
const cursor = db
  .collection('inventory')
  .find({
    status: 'A'
  })
  .project({ item: 1, status: 1, instock: { $slice: -1 } });
$cursor = $db->inventory->find(
    ['status' => 'A'],
    ['projection' => ['item' => 1, 'status' => 1, 'instock' => ['$slice' => -1]]]
);
cursor = db.inventory.find(
    {"status": "A"},
    {"item": 1, "status": 1, "instock": {"$slice": -1}})
findPublisher = collection.find(eq("status", "A"))
        .projection(fields(include("item", "status"), slice("instock", -1)));
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();
$cursor = $db->coll("inventory")->find(
    { status => "A" },
    { projection => { item => 1, status => 1, instock => { '$slice' => -1 } } }
);
client[:inventory].find({ status: 'A' },
                        projection: {'item' => 1,
                                     'status' => 1,
                                     'instock' => { '$slice' => -1 } })
findObservable = collection.find(equal("status", "A"))
  .projection(fields(include("item", "status"), slice("instock", -1)))
projection := bson.D{
	{"item", 1},
	{"status", 1},
	{"instock", bson.D{
		{"$slice", -1},
	}},
}

cursor, err := coll.Find(
	context.Background(),
	bson.D{
		{"status", "A"},
	},
	options.Find().SetProjection(projection),
)

$elemMatch, $slice, and $ are the only way 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 will not project the array with the first element.例如,不能使用数组索引投影特定数组元素;例如,{ "instock.0": 1 }投影将不会投影具有第一个元素的数组。

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数组中的最后一个元素:

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

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

    { item: 1, status: 1, instock: { $slice: -1 } }
  4. Click Find.点击“查找”。
cursor = db.inventory.find(
    {"status": "A"},
    {"item": 1, "status": 1, "instock": {"$slice": -1}})

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"), slice("instock", -1)));
const cursor = db
  .collection('inventory')
  .find({
    status: 'A'
  })
  .project({ item: 1, status: 1, instock: { $slice: -1 } });
$cursor = $db->inventory->find(
    ['status' => 'A'],
    ['projection' => ['item' => 1, 'status' => 1, 'instock' => ['$slice' => -1]]]
);
cursor = db.inventory.find(
    {"status": "A"},
    {"item": 1, "status": 1, "instock": {"$slice": -1}})
findPublisher = collection.find(eq("status", "A"))
        .projection(fields(include("item", "status"), slice("instock", -1)));
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();
$cursor = $db->coll("inventory")->find(
    { status => "A" },
    { projection => { item => 1, status => 1, instock => { '$slice' => -1 } } }
);
client[:inventory].find({ status: 'A' },
                        projection: {'item' => 1,
                                     'status' => 1,
                                     'instock' => { '$slice' => -1 } })
findObservable = collection.find(equal("status", "A"))
  .projection(fields(include("item", "status"), slice("instock", -1)))
projection := bson.D{
	{"item", 1},
	{"status", 1},
	{"instock", bson.D{
		{"$slice", -1},
	}},
}

cursor, err := coll.Find(
	context.Background(),
	bson.D{
		{"status", "A"},
	},
	options.Find().SetProjection(projection),
)

$elemMatch, $slice, and $ are the only way 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 will not project the array with the first element.例如,不能使用数组索引投影特定的数组元素;例如,[ "instock.0" => 1 ]投影不会投影具有第一个元素的数组。

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

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

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

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

    { item: 1, status: 1, instock: { $slice: -1 } }
  4. Click Find.点击“查找”。
cursor = db.inventory.find(
    {"status": "A"},
    {"item": 1, "status": 1, "instock": {"$slice": -1}})

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"), slice("instock", -1)));
const cursor = db
  .collection('inventory')
  .find({
    status: 'A'
  })
  .project({ item: 1, status: 1, instock: { $slice: -1 } });
$cursor = $db->inventory->find(
    ['status' => 'A'],
    ['projection' => ['item' => 1, 'status' => 1, 'instock' => ['$slice' => -1]]]
);
cursor = db.inventory.find(
    {"status": "A"},
    {"item": 1, "status": 1, "instock": {"$slice": -1}})
findPublisher = collection.find(eq("status", "A"))
        .projection(fields(include("item", "status"), slice("instock", -1)));
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();
$cursor = $db->coll("inventory")->find(
    { status => "A" },
    { projection => { item => 1, status => 1, instock => { '$slice' => -1 } } }
);
client[:inventory].find({ status: 'A' },
                        projection: {'item' => 1,
                                     'status' => 1,
                                     'instock' => { '$slice' => -1 } })
findObservable = collection.find(equal("status", "A"))
  .projection(fields(include("item", "status"), slice("instock", -1)))
projection := bson.D{
	{"item", 1},
	{"status", 1},
	{"instock", bson.D{
		{"$slice", -1},
	}},
}

cursor, err := coll.Find(
	context.Background(),
	bson.D{
		{"status", "A"},
	},
	options.Find().SetProjection(projection),
)

$elemMatch, $slice, and $ are the only way 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. include("instock.0") projection will not project the array with the first element.例如,不能使用数组索引投影特定的数组元素;例如,include("instock.0")投影不会投影第一个元素的数组。

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

The following example uses the $slice projection operator to return the last element in the instock array:

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

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

    { item: 1, status: 1, instock: { $slice: -1 } }
  4. Click Find.点击“查找”。
cursor = db.inventory.find(
    {"status": "A"},
    {"item": 1, "status": 1, "instock": {"$slice": -1}})

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"), slice("instock", -1)));
const cursor = db
  .collection('inventory')
  .find({
    status: 'A'
  })
  .project({ item: 1, status: 1, instock: { $slice: -1 } });
$cursor = $db->inventory->find(
    ['status' => 'A'],
    ['projection' => ['item' => 1, 'status' => 1, 'instock' => ['$slice' => -1]]]
);
cursor = db.inventory.find(
    {"status": "A"},
    {"item": 1, "status": 1, "instock": {"$slice": -1}})
findPublisher = collection.find(eq("status", "A"))
        .projection(fields(include("item", "status"), slice("instock", -1)));
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();
$cursor = $db->coll("inventory")->find(
    { status => "A" },
    { projection => { item => 1, status => 1, instock => { '$slice' => -1 } } }
);
client[:inventory].find({ status: 'A' },
                        projection: {'item' => 1,
                                     'status' => 1,
                                     'instock' => { '$slice' => -1 } })
findObservable = collection.find(equal("status", "A"))
  .projection(fields(include("item", "status"), slice("instock", -1)))
projection := bson.D{
	{"item", 1},
	{"status", 1},
	{"instock", bson.D{
		{"$slice", -1},
	}},
}

cursor, err := coll.Find(
	context.Background(),
	bson.D{
		{"status", "A"},
	},
	options.Find().SetProjection(projection),
)

$elemMatch, $slice, and $ are the only way to project specific elements to include in the returned array.

For example, the following operation will not project the array with the first element:

Builders<BsonDocument>.Projection.Include("instock.0")

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

The following example uses the $slice projection operator to return the last element in the instock array:

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

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

    { item: 1, status: 1, instock: { $slice: -1 } }
  4. Click Find.点击“查找”。
cursor = db.inventory.find(
    {"status": "A"},
    {"item": 1, "status": 1, "instock": {"$slice": -1}})

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"), slice("instock", -1)));
const cursor = db
  .collection('inventory')
  .find({
    status: 'A'
  })
  .project({ item: 1, status: 1, instock: { $slice: -1 } });
$cursor = $db->inventory->find(
    ['status' => 'A'],
    ['projection' => ['item' => 1, 'status' => 1, 'instock' => ['$slice' => -1]]]
);
cursor = db.inventory.find(
    {"status": "A"},
    {"item": 1, "status": 1, "instock": {"$slice": -1}})
findPublisher = collection.find(eq("status", "A"))
        .projection(fields(include("item", "status"), slice("instock", -1)));
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();
$cursor = $db->coll("inventory")->find(
    { status => "A" },
    { projection => { item => 1, status => 1, instock => { '$slice' => -1 } } }
);
client[:inventory].find({ status: 'A' },
                        projection: {'item' => 1,
                                     'status' => 1,
                                     'instock' => { '$slice' => -1 } })
findObservable = collection.find(equal("status", "A"))
  .projection(fields(include("item", "status"), slice("instock", -1)))
projection := bson.D{
	{"item", 1},
	{"status", 1},
	{"instock", bson.D{
		{"$slice", -1},
	}},
}

cursor, err := coll.Find(
	context.Background(),
	bson.D{
		{"status", "A"},
	},
	options.Find().SetProjection(projection),
)

$elemMatch, $slice, and $ are the only way 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 will not project the array with the first element.

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

The following example uses the $slice projection operator to return the last element in the instock array:

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

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

    { item: 1, status: 1, instock: { $slice: -1 } }
  4. Click Find.点击“查找”。
cursor = db.inventory.find(
    {"status": "A"},
    {"item": 1, "status": 1, "instock": {"$slice": -1}})

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"), slice("instock", -1)));
const cursor = db
  .collection('inventory')
  .find({
    status: 'A'
  })
  .project({ item: 1, status: 1, instock: { $slice: -1 } });
$cursor = $db->inventory->find(
    ['status' => 'A'],
    ['projection' => ['item' => 1, 'status' => 1, 'instock' => ['$slice' => -1]]]
);
cursor = db.inventory.find(
    {"status": "A"},
    {"item": 1, "status": 1, "instock": {"$slice": -1}})
findPublisher = collection.find(eq("status", "A"))
        .projection(fields(include("item", "status"), slice("instock", -1)));
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();
$cursor = $db->coll("inventory")->find(
    { status => "A" },
    { projection => { item => 1, status => 1, instock => { '$slice' => -1 } } }
);
client[:inventory].find({ status: 'A' },
                        projection: {'item' => 1,
                                     'status' => 1,
                                     'instock' => { '$slice' => -1 } })
findObservable = collection.find(equal("status", "A"))
  .projection(fields(include("item", "status"), slice("instock", -1)))
projection := bson.D{
	{"item", 1},
	{"status", 1},
	{"instock", bson.D{
		{"$slice", -1},
	}},
}

cursor, err := coll.Find(
	context.Background(),
	bson.D{
		{"status", "A"},
	},
	options.Find().SetProjection(projection),
)

$elemMatch, $slice, and $ are the only way 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 will not project the array with the first element.

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

The following example uses the $slice projection operator to return the last element in the instock array:

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

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

    { item: 1, status: 1, instock: { $slice: -1 } }
  4. Click Find.点击“查找”。
cursor = db.inventory.find(
    {"status": "A"},
    {"item": 1, "status": 1, "instock": {"$slice": -1}})

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"), slice("instock", -1)));
const cursor = db
  .collection('inventory')
  .find({
    status: 'A'
  })
  .project({ item: 1, status: 1, instock: { $slice: -1 } });
$cursor = $db->inventory->find(
    ['status' => 'A'],
    ['projection' => ['item' => 1, 'status' => 1, 'instock' => ['$slice' => -1]]]
);
cursor = db.inventory.find(
    {"status": "A"},
    {"item": 1, "status": 1, "instock": {"$slice": -1}})
findPublisher = collection.find(eq("status", "A"))
        .projection(fields(include("item", "status"), slice("instock", -1)));
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();
$cursor = $db->coll("inventory")->find(
    { status => "A" },
    { projection => { item => 1, status => 1, instock => { '$slice' => -1 } } }
);
client[:inventory].find({ status: 'A' },
                        projection: {'item' => 1,
                                     'status' => 1,
                                     'instock' => { '$slice' => -1 } })
findObservable = collection.find(equal("status", "A"))
  .projection(fields(include("item", "status"), slice("instock", -1)))
projection := bson.D{
	{"item", 1},
	{"status", 1},
	{"instock", bson.D{
		{"$slice", -1},
	}},
}

cursor, err := coll.Find(
	context.Background(),
	bson.D{
		{"status", "A"},
	},
	options.Find().SetProjection(projection),
)

$elemMatch, $slice, and $ are the only way 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. include("instock.0") projection will not project the array with the first element.

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

The following example uses the $slice projection operator to return the last element in the instock array:

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

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

    { item: 1, status: 1, instock: { $slice: -1 } }
  4. Click Find.点击“查找”。
cursor = db.inventory.find(
    {"status": "A"},
    {"item": 1, "status": 1, "instock": {"$slice": -1}})

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"), slice("instock", -1)));
const cursor = db
  .collection('inventory')
  .find({
    status: 'A'
  })
  .project({ item: 1, status: 1, instock: { $slice: -1 } });
$cursor = $db->inventory->find(
    ['status' => 'A'],
    ['projection' => ['item' => 1, 'status' => 1, 'instock' => ['$slice' => -1]]]
);
cursor = db.inventory.find(
    {"status": "A"},
    {"item": 1, "status": 1, "instock": {"$slice": -1}})
findPublisher = collection.find(eq("status", "A"))
        .projection(fields(include("item", "status"), slice("instock", -1)));
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();
$cursor = $db->coll("inventory")->find(
    { status => "A" },
    { projection => { item => 1, status => 1, instock => { '$slice' => -1 } } }
);
client[:inventory].find({ status: 'A' },
                        projection: {'item' => 1,
                                     'status' => 1,
                                     'instock' => { '$slice' => -1 } })
findObservable = collection.find(equal("status", "A"))
  .projection(fields(include("item", "status"), slice("instock", -1)))
projection := bson.D{
	{"item", 1},
	{"status", 1},
	{"instock", bson.D{
		{"$slice", -1},
	}},
}

cursor, err := coll.Find(
	context.Background(),
	bson.D{
		{"status", "A"},
	},
	options.Find().SetProjection(projection),
)

$elemMatch, $slice, and $ are the only way 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. include("instock.0") projection will not project the array with the first element.

Additional Considerations其他考虑事项

Starting in MongoDB 4.4, MongoDB enforces additional restrictions with regards to projections. 从MongoDB 4.4开始,MongoDB对投影实施额外的限制。See Projection Restrictions for details.有关详细信息,请参阅投影限制