Project Fields to Return from Query

This page provides examples in:

By default, queries in MongoDB return all fields in matching documents.To limit the amount of data that MongoDB sends to applications, you caninclude a projection document to specify or restrict fields toreturn.

  • Mongo Shell
  • Compass
  • Python
  • Java (Sync)
  • Node.js
  • Other
    • PHP
    • Motor
    • Java (Async)
    • C#
    • Perl
    • Ruby
    • Scala
    • Go

This page provides examples of query operations with projection using thedb.collection.find() method in themongo shell. The examples on this page use theinventory collection. To populate the inventorycollection, run the following:

This page provides examples of query operations with projection usingMongoDB Compass. The examples on thispage use the inventory collection. Populate theinventory collection with the following documents:

This page provides examples of query operations with projection using thepymongo.collection.Collection.find() method in thePyMongoPython driver. The examples on this page use the inventorycollection. To populate the inventory collection, run thefollowing:

This page provides examples of query operations with projection using thecom.mongodb.client.MongoCollection.find method in the MongoDBJava Synchronous Driver.

Tip

The driver provides com.mongodb.client.model.Filtershelper methods to facilitate the creation of filterdocuments. The examples on this page use these methods tocreate the filter documents.

The examples on this page use the inventorycollection. To populate the inventory collection, run thefollowing:

This page provides examples of query operations with projection using theCollection.find() method inthe MongoDB Node.js Driver.The examples on this page use the inventory collection. Topopulate the inventory collection, run the following:

This page provides examples of query operations with projection using theMongoDB\Collection::find()method in theMongoDB PHP Library.The examples on this page use the inventory collection. Topopulate the inventory collection, run the following:

This page provides examples of query operations with projection using themotor.motor_asyncio.AsyncIOMotorCollection.find()method in the Motordriver. The examples on this page use the inventorycollection. To populate the inventory collection, run thefollowing:

This page provides examples of query operations with projection using thecom.mongodb.reactivestreams.client.MongoCollection.find)method in the MongoDB Java Reactive Streams Driver.

The examples on this page use the inventorycollection. To populate the inventory collection, run thefollowing:

This page provides examples of query operations with projection using theMongoCollection.Find()method in theMongoDB C# Driver.The examples on this page use the inventory collection. Topopulate the inventory collection, run the following:

This page provides examples of query operations with projection using theMongoDB::Collection::find() methodin theMongoDB Perl Driver.The examples on this page use the inventory collection. Topopulate the inventory collection, run the following:

This page provides examples of query operations with projection using theMongo::Collection#find()method in theMongoDB Ruby Driver.The examples on this page use the inventory collection. Topopulate the inventory collection, run the following:

This page provides examples of query operations with projection using thecollection.find()(implicite:org.mongodb.scala.bson.DefaultHelper.DefaultsTo[C,TResult],implicitct:scala.reflect.ClassTag[C]):org.mongodb.scala.FindObservable[C]) methodin theMongoDB Scala Driver.The examples on this page use the inventory collection. Topopulate the inventory collection, run the following:

This page provides examples of query operations with projection using theCollection.Findfunction in theMongoDB Go Driver.The examples on this page use the inventory collection. Topopulate the inventory collection, run the following:

  • Mongo Shell
  • Compass
  • Python
  • Java (Sync)
  • Node.js
  • Other
    • PHP
    • Motor
    • Java (Async)
    • C#
    • Perl
    • Ruby
    • Scala
    • Go
  1. db.inventory.insertMany( [
  2. { item: "journal", status: "A", size: { h: 14, w: 21, uom: "cm" }, instock: [ { warehouse: "A", qty: 5 } ] },
  3. { item: "notebook", status: "A", size: { h: 8.5, w: 11, uom: "in" }, instock: [ { warehouse: "C", qty: 5 } ] },
  4. { item: "paper", status: "D", size: { h: 8.5, w: 11, uom: "in" }, instock: [ { warehouse: "A", qty: 60 } ] },
  5. { item: "planner", status: "D", size: { h: 22.85, w: 30, uom: "cm" }, instock: [ { warehouse: "A", qty: 40 } ] },
  6. { item: "postcard", status: "A", size: { h: 10, w: 15.25, uom: "cm" }, instock: [ { warehouse: "B", qty: 15 }, { warehouse: "C", qty: 35 } ] }
  7. ]);

You can run the operation in the web shell below:

  1. [
  2. { item: "journal", status: "A", size: { h: 14, w: 21, uom: "cm" }, instock: [ { warehouse: "A", qty: 5 } ] },
  3. { item: "notebook", status: "A", size: { h: 8.5, w: 11, uom: "in" }, instock: [ { warehouse: "C", qty: 5 } ] },
  4. { item: "paper", status: "D", size: { h: 8.5, w: 11, uom: "in" }, instock: [ { warehouse: "A", qty: 60 } ] },
  5. { item: "planner", status: "D", size: { h: 22.85, w: 30, uom: "cm" }, instock: [ { warehouse: "A", qty: 40 } ] },
  6. { item: "postcard", status: "A", size: { h: 10, w: 15.25, uom: "cm" }, instock: [ { warehouse: "B", qty: 15 }, { warehouse: "C", qty: 35 } ] }
  7. ]

For instructions on inserting documents in MongoDB Compass,see Insert Documents.

  1. db.inventory.insert_many([
  2. {"item": "journal",
  3. "status": "A",
  4. "size": {"h": 14, "w": 21, "uom": "cm"},
  5. "instock": [{"warehouse": "A", "qty": 5}]},
  6. {"item": "notebook",
  7. "status": "A",
  8. "size": {"h": 8.5, "w": 11, "uom": "in"},
  9. "instock": [{"warehouse": "C", "qty": 5}]},
  10. {"item": "paper",
  11. "status": "D",
  12. "size": {"h": 8.5, "w": 11, "uom": "in"},
  13. "instock": [{"warehouse": "A", "qty": 60}]},
  14. {"item": "planner",
  15. "status": "D",
  16. "size": {"h": 22.85, "w": 30, "uom": "cm"},
  17. "instock": [{"warehouse": "A", "qty": 40}]},
  18. {"item": "postcard",
  19. "status": "A",
  20. "size": {"h": 10, "w": 15.25, "uom": "cm"},
  21. "instock": [
  22. {"warehouse": "B", "qty": 15},
  23. {"warehouse": "C", "qty": 35}]}])
  1. collection.insertMany(asList(
  2. Document.parse("{ item: 'journal', status: 'A', size: { h: 14, w: 21, uom: 'cm' }, instock: [ { warehouse: 'A', qty: 5 }]}"),
  3. Document.parse("{ item: 'notebook', status: 'A', size: { h: 8.5, w: 11, uom: 'in' }, instock: [ { warehouse: 'C', qty: 5}]}"),
  4. Document.parse("{ item: 'paper', status: 'D', size: { h: 8.5, w: 11, uom: 'in' }, instock: [ { warehouse: 'A', qty: 60 }]}"),
  5. Document.parse("{ item: 'planner', status: 'D', size: { h: 22.85, w: 30, uom: 'cm' }, instock: [ { warehouse: 'A', qty: 40}]}"),
  6. Document.parse("{ item: 'postcard', status: 'A', size: { h: 10, w: 15.25, uom: 'cm' }, "
  7. + "instock: [ { warehouse: 'B', qty: 15 }, { warehouse: 'C', qty: 35 } ] }")
  8. ));
  1. await db.collection('inventory').insertMany([
  2. {
  3. item: 'journal',
  4. status: 'A',
  5. size: { h: 14, w: 21, uom: 'cm' },
  6. instock: [{ warehouse: 'A', qty: 5 }]
  7. },
  8. {
  9. item: 'notebook',
  10. status: 'A',
  11. size: { h: 8.5, w: 11, uom: 'in' },
  12. instock: [{ warehouse: 'C', qty: 5 }]
  13. },
  14. {
  15. item: 'paper',
  16. status: 'D',
  17. size: { h: 8.5, w: 11, uom: 'in' },
  18. instock: [{ warehouse: 'A', qty: 60 }]
  19. },
  20. {
  21. item: 'planner',
  22. status: 'D',
  23. size: { h: 22.85, w: 30, uom: 'cm' },
  24. instock: [{ warehouse: 'A', qty: 40 }]
  25. },
  26. {
  27. item: 'postcard',
  28. status: 'A',
  29. size: { h: 10, w: 15.25, uom: 'cm' },
  30. instock: [{ warehouse: 'B', qty: 15 }, { warehouse: 'C', qty: 35 }]
  31. }
  32. ]);
  1. $insertManyResult = $db->inventory->insertMany([
  2. [
  3. 'item' => 'journal',
  4. 'status' => 'A',
  5. 'size' => ['h' => 14, 'w' => 21, 'uom' => 'cm'],
  6. 'instock' => [
  7. ['warehouse' => 'A', 'qty' => 5],
  8. ],
  9. ],
  10. [
  11. 'item' => 'notebook',
  12. 'status' => 'A',
  13. 'size' => ['h' => 8.5, 'w' => 11, 'uom' => 'in'],
  14. 'instock' => [
  15. ['warehouse' => 'C', 'qty' => 5],
  16. ],
  17. ],
  18. [
  19. 'item' => 'paper',
  20. 'status' => 'D',
  21. 'size' => ['h' => 8.5, 'w' => 11, 'uom' => 'in'],
  22. 'instock' => [
  23. ['warehouse' => 'A', 'qty' => 60],
  24. ],
  25. ],
  26. [
  27. 'item' => 'planner',
  28. 'status' => 'D',
  29. 'size' => ['h' => 22.85, 'w' => 30, 'uom' => 'cm'],
  30. 'instock' => [
  31. ['warehouse' => 'A', 'qty' => 40],
  32. ],
  33. ],
  34. [
  35. 'item' => 'postcard',
  36. 'status' => 'A',
  37. 'size' => ['h' => 10, 'w' => 15.25, 'uom' => 'cm'],
  38. 'instock' => [
  39. ['warehouse' => 'B', 'qty' => 15],
  40. ['warehouse' => 'C', 'qty' => 35],
  41. ],
  42. ],
  43. ]);
  1. await db.inventory.insert_many([
  2. {"item": "journal",
  3. "status": "A",
  4. "size": {"h": 14, "w": 21, "uom": "cm"},
  5. "instock": [{"warehouse": "A", "qty": 5}]},
  6. {"item": "notebook",
  7. "status": "A",
  8. "size": {"h": 8.5, "w": 11, "uom": "in"},
  9. "instock": [{"warehouse": "C", "qty": 5}]},
  10. {"item": "paper",
  11. "status": "D",
  12. "size": {"h": 8.5, "w": 11, "uom": "in"},
  13. "instock": [{"warehouse": "A", "qty": 60}]},
  14. {"item": "planner",
  15. "status": "D",
  16. "size": {"h": 22.85, "w": 30, "uom": "cm"},
  17. "instock": [{"warehouse": "A", "qty": 40}]},
  18. {"item": "postcard",
  19. "status": "A",
  20. "size": {"h": 10, "w": 15.25, "uom": "cm"},
  21. "instock": [
  22. {"warehouse": "B", "qty": 15},
  23. {"warehouse": "C", "qty": 35}]}])
  1. Publisher<Success> insertManyPublisher = collection.insertMany(asList(
  2. Document.parse("{ item: 'journal', status: 'A', size: { h: 14, w: 21, uom: 'cm' }, instock: [ { warehouse: 'A', qty: 5 }]}"),
  3. Document.parse("{ item: 'notebook', status: 'A', size: { h: 8.5, w: 11, uom: 'in' }, instock: [ { warehouse: 'C', qty: 5}]}"),
  4. Document.parse("{ item: 'paper', status: 'D', size: { h: 8.5, w: 11, uom: 'in' }, instock: [ { warehouse: 'A', qty: 60 }]}"),
  5. Document.parse("{ item: 'planner', status: 'D', size: { h: 22.85, w: 30, uom: 'cm' }, instock: [ { warehouse: 'A', qty: 40}]}"),
  6. Document.parse("{ item: 'postcard', status: 'A', size: { h: 10, w: 15.25, uom: 'cm' }, "
  7. + "instock: [ { warehouse: 'B', qty: 15 }, { warehouse: 'C', qty: 35 } ] }")
  8. ));
  1. var documents = new[]
  2. {
  3. new BsonDocument
  4. {
  5. { "item", "journal" },
  6. { "status", "A" },
  7. { "size", new BsonDocument { { "h", 14 }, { "w", 21 }, { "uom", "cm" } } },
  8. { "instock", new BsonArray
  9. {
  10. new BsonDocument { { "warehouse", "A" }, { "qty", 5 } } }
  11. }
  12. },
  13. new BsonDocument
  14. {
  15. { "item", "notebook" },
  16. { "status", "A" },
  17. { "size", new BsonDocument { { "h", 8.5 }, { "w", 11 }, { "uom", "in" } } },
  18. { "instock", new BsonArray
  19. {
  20. new BsonDocument { { "warehouse", "C" }, { "qty", 5 } } }
  21. }
  22. },
  23. new BsonDocument
  24. {
  25. { "item", "paper" },
  26. { "status", "D" },
  27. { "size", new BsonDocument { { "h", 8.5 }, { "w", 11 }, { "uom", "in" } } },
  28. { "instock", new BsonArray
  29. {
  30. new BsonDocument { { "warehouse", "A" }, { "qty", 60 } } }
  31. }
  32. },
  33. new BsonDocument
  34. {
  35. { "item", "planner" },
  36. { "status", "D" },
  37. { "size", new BsonDocument { { "h", 22.85 }, { "w", 30 }, { "uom", "cm" } } },
  38. { "instock", new BsonArray
  39. {
  40. new BsonDocument { { "warehouse", "A" }, { "qty", 40 } } }
  41. }
  42. },
  43. new BsonDocument
  44. {
  45. { "item", "postcard" },
  46. { "status", "A" },
  47. { "size", new BsonDocument { { "h", 10 }, { "w", 15.25 }, { "uom", "cm" } } },
  48. { "instock", new BsonArray
  49. {
  50. new BsonDocument { { "warehouse", "B" }, { "qty", 15 } },
  51. new BsonDocument { { "warehouse", "C" }, { "qty", 35 } } }
  52. }
  53. }
  54. };
  55. collection.InsertMany(documents);
  1. $db->coll("inventory")->insert_many(
  2. [
  3. {
  4. item => "journal",
  5. status => "A",
  6. size => { h => 14, w => 21, uom => "cm" },
  7. instock => [ { warehouse => "A", qty => 5 } ]
  8. },
  9. {
  10. item => "notebook",
  11. status => "A",
  12. size => { h => 8.5, w => 11, uom => "in" },
  13. instock => [ { warehouse => "C", qty => 5 } ]
  14. },
  15. {
  16. item => "paper",
  17. status => "D",
  18. size => { h => 8.5, w => 11, uom => "in" },
  19. instock => [ { warehouse => "A", qty => 60 } ]
  20. },
  21. {
  22. item => "planner",
  23. status => "D",
  24. size => { h => 22.85, w => 30, uom => "cm" },
  25. instock => [ { warehouse => "A", qty => 40 } ]
  26. },
  27. {
  28. item => "postcard",
  29. status => "A",
  30. size => { h => 10, w => 15.25, uom => "cm" },
  31. instock => [
  32. { warehouse => "B", qty => 15 },
  33. { warehouse => "C", qty => 35 }
  34. ]
  35. }
  36. ]
  37. );
  1. client[:inventory].insert_many([{ item: 'journal',
  2. status: 'A',
  3. size: { h: 14, w: 21, uom: 'cm' },
  4. instock: [ { warehouse: 'A', qty: 5 }] },
  5. { item: 'notebook',
  6. status: 'A',
  7. size: { h: 8.5, w: 11, uom: 'in' },
  8. instock: [ { warehouse: 'C', qty: 5 }] },
  9. { item: 'paper',
  10. status: 'D',
  11. size: { h: 8.5, w: 11, uom: 'in' },
  12. instock: [ { warehouse: 'A', qty: 60 }] },
  13. { item: 'planner',
  14. status: 'D',
  15. size: { h: 22.85, w: 30, uom: 'cm' },
  16. instock: [ { warehouse: 'A', qty: 40 }] },
  17. { item: 'postcard',
  18. status: 'A',
  19. size: { h: 10, w: 15.25, uom: 'cm' },
  20. instock: [ { warehouse: 'B', qty: 15 },
  21. { warehouse: 'C', qty: 35 }] }])
  1. collection.insertMany(Seq(
  2. Document("""{ item: "journal", status: "A", size: { h: 14, w: 21, uom: "cm" }, instock: [ { warehouse: "A", qty: 5 } ] }"""),
  3. Document("""{ item: "notebook", status: "A", size: { h: 8.5, w: 11, uom: "in" }, instock: [ { warehouse: "C", qty: 5 } ] }"""),
  4. Document("""{ item: "paper", status: "D", size: { h: 8.5, w: 11, uom: "in" }, instock: [ { warehouse: "A", qty: 60 } ] }"""),
  5. Document("""{ item: "planner", status: "D", size: { h: 22.85, w: 30, uom: "cm" }, instock: [ { warehouse: "A", qty: 40 } ] }"""),
  6. Document("""{ item: "postcard", status: "A", size: { h: 10, w: 15.25, uom: "cm" },
  7. instock: [ { warehouse: "B", qty: 15 }, { warehouse: "C", qty: 35 } ] }""")
  8.  
  9. )).execute()
  1. docs := []interface{}{
  2. bson.D{
  3. {"item", "journal"},
  4. {"status", "A"},
  5. {"size", bson.D{
  6. {"h", 14},
  7. {"w", 21},
  8. {"uom", "cm"},
  9. }},
  10. {"instock", bson.A{
  11. bson.D{
  12. {"warehouse", "A"},
  13. {"qty", 5},
  14. },
  15. }},
  16. },
  17. bson.D{
  18. {"item", "notebook"},
  19. {"status", "A"},
  20. {"size", bson.D{
  21. {"h", 8.5},
  22. {"w", 11},
  23. {"uom", "in"},
  24. }},
  25. {"instock", bson.A{
  26. bson.D{
  27. {"warehouse", "EC"},
  28. {"qty", 5},
  29. },
  30. }},
  31. },
  32. bson.D{
  33. {"item", "paper"},
  34. {"status", "D"},
  35. {"size", bson.D{
  36. {"h", 8.5},
  37. {"w", 11},
  38. {"uom", "in"},
  39. }},
  40. {"instock", bson.A{
  41. bson.D{
  42. {"warehouse", "A"},
  43. {"qty", 60},
  44. },
  45. }},
  46. },
  47. bson.D{
  48. {"item", "planner"},
  49. {"status", "D"},
  50. {"size", bson.D{
  51. {"h", 22.85},
  52. {"w", 30},
  53. {"uom", "cm"},
  54. }},
  55. {"instock", bson.A{
  56. bson.D{
  57. {"warehouse", "A"},
  58. {"qty", 40},
  59. },
  60. }},
  61. },
  62. bson.D{
  63. {"item", "postcard"},
  64. {"status", "A"},
  65. {"size", bson.D{
  66. {"h", 10},
  67. {"w", 15.25},
  68. {"uom", "cm"},
  69. }},
  70. {"instock", bson.A{
  71. bson.D{
  72. {"warehouse", "B"},
  73. {"qty", 15},
  74. },
  75. bson.D{
  76. {"warehouse", "EC"},
  77. {"qty", 35},
  78. },
  79. }},
  80. },
  81. }
  82.  
  83. result, err := coll.InsertMany(context.Background(), docs)

Return All Fields in Matching Documents

  • Mongo Shell
  • Compass
  • Python
  • Java (Sync)
  • Node.js
  • Other
    • PHP
    • Java (Async)
    • C#
    • Perl
    • Ruby
    • Scala

If you do not specify a projection document, thedb.collection.find() method returns all fields in thematching documents.

If you do not specify a projection document, Compassreturns all fields in the matching documents.

If you do not specify a projection document, thefind() method returnsall fields in the matching documents.

If you do not specify a projection, thecom.mongodb.client.MongoCollection.find method returns allfields in the matching documents.

If you do not specify a projection document, thefind() method yields allfields in the matching documents.

If you do not specify a projection document, thefind()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.

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

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

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

If you do not specify a projection, thecollection.find()(implicite:org.mongodb.scala.bson.DefaultHelper.DefaultsTo[C,TResult],implicitct:scala.reflect.ClassTag[C]):org.mongodb.scala.FindObservable[C])method returns all fields in the matching documents.

The following example returns all fields from all documents in theinventory collection where the status equals "A":

  • Mongo Shell
  • Compass
  • Python
  • Java (Sync)
  • Node.js
  • Other
    • PHP
    • Motor
    • Java (Async)
    • C#
    • Perl
    • Ruby
    • Scala
    • Go
  1. db.inventory.find( { status: "A" } )

Copy the following expression into the Filter barand click Find:

  1. { status: "A" }

../../_images/compass-project-all-fields.png

  1. cursor = db.inventory.find({"status": "A"})
  1. FindIterable<Document> findIterable = collection.find(eq("status", "A"));
  1. const cursor = db.collection('inventory').find({
  2. status: 'A'
  3. });
  1. $cursor = $db->inventory->find(['status' => 'A']);
  1. cursor = db.inventory.find({"status": "A"})
  1. FindPublisher<Document> findPublisher = collection.find(eq("status", "A"));
  1. var filter = Builders<BsonDocument>.Filter.Eq("status", "A");
  2. var result = collection.Find(filter).ToList();
  1. $cursor = $db->coll("inventory")->find( { status => "A" } );
  1. client[:inventory].find(status: 'A')
  1. var findObservable = collection.find(equal("status", "A"))
  1. cursor, err := coll.Find(
  2. context.Background(),
  3. bson.D{{"status", "A"}},
  4. )

The operation corresponds to the following SQL statement:

  1. SELECT * from inventory WHERE status = "A"

Return the Specified Fields and the _id Field Only

A projection can explicitly include several fields by setting the<field> to 1 in the projection document. The followingoperation returns all documents that match the query. In the resultset, only the item, status and, by default, the _id fieldsreturn in the matching documents.

  • Mongo Shell
  • Compass
  • Python
  • Java (Sync)
  • Node.js
  • Other
    • PHP
    • Motor
    • Java (Async)
    • C#
    • Perl
    • Ruby
    • Scala
    • Go
  1. db.inventory.find( { status: "A" }, { item: 1, status: 1 } )

Copy the following expression into the Filter bar:

  1. { status: "A" }

Copy the following expression into the Projectbar:

  1. { item: 1, status: 1 }

Click Find.

../../_images/compass-project-specified-plus-id.png

  1. cursor = db.inventory.find(
  2. {"status": "A"}, {"item": 1, "status": 1})

To specify a projection document, chain thecom.mongodb.client.FindIterable.projection method to thefind method. The example uses thecom.mongodb.client.model.Projections class to create theprojection documents.

  1. findIterable = collection.find(eq("status", "A")).projection(include("item", "status"));
  1. const cursor = db
  2. .collection('inventory')
  3. .find({
  4. status: 'A'
  5. })
  6. .project({ item: 1, status: 1 });
  1. $cursor = $db->inventory->find(
  2. ['status' => 'A'],
  3. ['projection' => ['item' => 1, 'status' => 1]]
  4. );
  1. cursor = db.inventory.find(
  2. {"status": "A"}, {"item": 1, "status": 1})
  1. findPublisher = collection.find(eq("status", "A")).projection(include("item", "status"));
  1. var filter = Builders<BsonDocument>.Filter.Eq("status", "A");
  2. var projection = Builders<BsonDocument>.Projection.Include("item").Include("status");
  3. var result = collection.Find<BsonDocument>(filter).Project(projection).ToList();
  1. $cursor = $db->coll("inventory")->find(
  2. { status => "A" }, { projection => { item => 1, status => 1 } }
  3. );
  1. client[:inventory].find({ status: 'A' },
  2. projection: { item: 1, status: 1 })
  1. findObservable = collection.find(equal("status", "A")).projection(include("item", "status"))
  1. projection := bson.D{
  2. {"item", 1},
  3. {"status", 1},
  4. }
  5.  
  6. cursor, err := coll.Find(
  7. context.Background(),
  8. bson.D{
  9. {"status", "A"},
  10. },
  11. options.Find().SetProjection(projection),
  12. )

The operation corresponds to the following SQL statement:

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

Suppress _id Field

You can remove the _id field from the results by setting it to0 in the projection, as in the following example:

  • Mongo Shell
  • Compass
  • Python
  • Java (Sync)
  • Node.js
  • Other
    • PHP
    • Motor
    • Java (Async)
    • C#
    • Perl
    • Ruby
    • Scala
    • Go
  1. db.inventory.find( { status: "A" }, { item: 1, status: 1, _id: 0 } )

Copy the following expression into the Filter bar:

  1. { status: "A" }

Copy the following expression into the Projectbar:

  1. { item: 1, status: 1, _id: 0 }

Click Find.

../../_images/compass-project-suppress-id.png

  1. cursor = db.inventory.find(
  2. {"status": "A"}, {"item": 1, "status": 1, "_id": 0})

To specify a projection document, chain thecom.mongodb.client.FindIterable.projection method to thefind method. The example uses thecom.mongodb.client.model.Projections class to create theprojection documents.

  1. findIterable = collection.find(eq("status", "A"))
  2. .projection(fields(include("item", "status"), excludeId()));
  1. const cursor = db
  2. .collection('inventory')
  3. .find({
  4. status: 'A'
  5. })
  6. .project({ item: 1, status: 1, _id: 0 });
  1. $cursor = $db->inventory->find(
  2. ['status' => 'A'],
  3. ['projection' => ['item' => 1, 'status' => 1, '_id' => 0]]
  4. );
  1. cursor = db.inventory.find(
  2. {"status": "A"}, {"item": 1, "status": 1, "_id": 0})
  1. findPublisher = collection.find(eq("status", "A"))
  2. .projection(fields(include("item", "status"), excludeId()));
  1. var filter = Builders<BsonDocument>.Filter.Eq("status", "A");
  2. var projection = Builders<BsonDocument>.Projection.Include("item").Include("status").Exclude("_id");
  3. var result = collection.Find<BsonDocument>(filter).Project(projection).ToList();
  1. $cursor = $db->coll("inventory")->find(
  2. { status => "A" }, { projection => { item => 1, status => 1, "_id" => 0 } }
  3. );
  1. client[:inventory].find({ status: 'A' },
  2. projection: { item: 1, status: 1, _id: 0 })
  1. findObservable = collection.find(equal("status", "A"))
  2. .projection(fields(include("item", "status"), excludeId()))
  1. projection := bson.D{
  2. {"item", 1},
  3. {"status", 1},
  4. {"_id", 0},
  5. }
  6.  
  7. cursor, err := coll.Find(
  8. context.Background(),
  9. bson.D{
  10. {"status", "A"},
  11. },
  12. options.Find().SetProjection(projection),
  13. )

The operation corresponds to the following SQL statement:

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

Note

With the exception of the _id field, you cannot combine inclusionand exclusion statements in projection documents.

Return All But the Excluded Fields

Instead of listing the fields to return in the matching document, youcan use a projection to exclude specific fields. The following examplewhich returns all fields except for the status and the instockfields in the matching documents:

  • Mongo Shell
  • Compass
  • Python
  • Java (Sync)
  • Node.js
  • Other
    • PHP
    • Motor
    • Java (Async)
    • C#
    • Perl
    • Ruby
    • Scala
    • Go
  1. db.inventory.find( { status: "A" }, { status: 0, instock: 0 } )

Copy the following expression into the Filter bar:

  1. { status: "A" }

Copy the following expression into the Projectbar:

  1. { status: 0, instock: 0 }

Click Find.

../../_images/compass-project-exclude-fields.png

  1. cursor = db.inventory.find(
  2. {"status": "A"}, {"status": 0, "instock": 0})

To specify a projection document, chain thecom.mongodb.client.FindIterable.projection method to thefind method. The example uses thecom.mongodb.client.model.Projections class to create theprojection documents.

  1. findIterable = collection.find(eq("status", "A")).projection(exclude("item", "status"));
  1. const cursor = db
  2. .collection('inventory')
  3. .find({
  4. status: 'A'
  5. })
  6. .project({ status: 0, instock: 0 });
  1. $cursor = $db->inventory->find(
  2. ['status' => 'A'],
  3. ['projection' => ['status' => 0, 'instock' => 0]]
  4. );
  1. cursor = db.inventory.find(
  2. {"status": "A"}, {"status": 0, "instock": 0})
  1. findPublisher = collection.find(eq("status", "A")).projection(exclude("item", "status"));
  1. var filter = Builders<BsonDocument>.Filter.Eq("status", "A");
  2. var projection = Builders<BsonDocument>.Projection.Exclude("status").Exclude("instock");
  3. var result = collection.Find<BsonDocument>(filter).Project(projection).ToList();
  1. $cursor = $db->coll("inventory")->find(
  2. { status => "A" }, { projection => { status => 0, instock => 0 } }
  3. );
  1. client[:inventory].find({ status: 'A' },
  2. projection: { status: 0, instock: 0 })
  1. findObservable = collection.find(equal("status", "A")).projection(exclude("item", "status"))
  1. projection := bson.D{
  2. {"status", 0},
  3. {"instock", 0},
  4. }
  5.  
  6. cursor, err := coll.Find(
  7. context.Background(),
  8. bson.D{
  9. {"status", "A"},
  10. },
  11. options.Find().SetProjection(projection),
  12. )

Note

With the exception of the _id field, you cannot combine inclusionand exclusion statements in projection documents.

Return Specific Fields in Embedded Documents

You can return specific fields in an embedded document. Use thedot notation to refer to the embeddedfield and set to 1 in the projection document.

The following example returns:

  • The _id field (returned by default),
  • The item field,
  • The status field,
  • The uom field in the size document.

The uom field remains embedded in the size document.

  • Mongo Shell
  • Compass
  • Python
  • Java (Sync)
  • Node.js
  • Other
    • PHP
    • Motor
    • Java (Async)
    • C#
    • Perl
    • Ruby
    • Scala
    • Go
  1. db.inventory.find(
  2. { status: "A" },
  3. { item: 1, status: 1, "size.uom": 1 }
  4. )

Copy the following expression into the Filter bar:

  1. { status: "A" }

Copy the following expression into the Projectbar:

  1. { item: 1, status: 1, "size.uom": 1 }

Click Find.

../../_images/compass-project-embedded-fields.png

  1. cursor = db.inventory.find(
  2. {"status": "A"}, {"item": 1, "status": 1, "size.uom": 1})

To specify a projection document, chain thecom.mongodb.client.FindIterable.projection method to thefind method. The example uses thecom.mongodb.client.model.Projections class to create theprojection documents.

  1. findIterable = collection.find(eq("status", "A")).projection(include("item", "status", "size.uom"));
  1. const cursor = db
  2. .collection('inventory')
  3. .find({
  4. status: 'A'
  5. })
  6. .project({ item: 1, status: 1, 'size.uom': 1 });
  1. $cursor = $db->inventory->find(
  2. ['status' => 'A'],
  3. ['projection' => ['item' => 1, 'status' => 1, 'size.uom' => 1]]
  4. );
  1. cursor = db.inventory.find(
  2. {"status": "A"}, {"item": 1, "status": 1, "size.uom": 1})
  1. findPublisher = collection.find(eq("status", "A")).projection(include("item", "status", "size.uom"));
  1. var filter = Builders<BsonDocument>.Filter.Eq("status", "A");
  2. var projection = Builders<BsonDocument>.Projection.Include("item").Include("status").Include("size.uom");
  3. var result = collection.Find<BsonDocument>(filter).Project(projection).ToList();
  1. $cursor = $db->coll("inventory")->find(
  2. { status => "A" }, { projection => { item => 1, status => 1, "size.uom" => 1 } }
  3. );
  1. client[:inventory].find({ status: 'A' },
  2. projection: { 'item' => 1, 'status' => 1, 'size.uom' => 1 })
  1. findObservable = collection.find(equal("status", "A")).projection(include("item", "status", "size.uom"))
  1. projection := bson.D{
  2. {"item", 1},
  3. {"status", 1},
  4. {"size.uom", 1},
  5. }
  6.  
  7. cursor, err := coll.Find(
  8. context.Background(),
  9. bson.D{
  10. {"status", "A"},
  11. },
  12. options.Find().SetProjection(projection),
  13. )

Suppress Specific Fields in Embedded Documents

You can suppress specific fields in an embedded document. Use thedot notation to refer to the embeddedfield in the projection document and set to 0.

The following example specifies a projection to exclude the uomfield inside the size document. All other fields are returned inthe matching documents:

  • Mongo Shell
  • Compass
  • Python
  • Java (Sync)
  • Node.js
  • Other
    • PHP
    • Motor
    • Java (Async)
    • C#
    • Perl
    • Ruby
    • Scala
    • Go
  1. db.inventory.find(
  2. { status: "A" },
  3. { "size.uom": 0 }
  4. )

Copy the following expression into the Filter bar:

  1. { status: "A" }

Copy the following expression into the Projectbar:

  1. { "size.uom": 0 }

Click Find.

../../_images/compass-project-suppress-embedded-field.png

  1. cursor = db.inventory.find({"status": "A"}, {"size.uom": 0})

To specify a projection document, chain thecom.mongodb.client.FindIterable.projection method to thefind method. The example uses thecom.mongodb.client.model.Projections class to create theprojection documents.

  1. findIterable = collection.find(eq("status", "A")).projection(exclude("size.uom"));
  1. const cursor = db
  2. .collection('inventory')
  3. .find({
  4. status: 'A'
  5. })
  6. .project({ 'size.uom': 0 });
  1. $cursor = $db->inventory->find(
  2. ['status' => 'A'],
  3. ['projection' => ['size.uom' => 0]]
  4. );
  1. cursor = db.inventory.find({"status": "A"}, {"size.uom": 0})
  1. findPublisher = collection.find(eq("status", "A")).projection(exclude("size.uom"));
  1. var filter = Builders<BsonDocument>.Filter.Eq("status", "A");
  2. var projection = Builders<BsonDocument>.Projection.Exclude("size.uom");
  3. var result = collection.Find<BsonDocument>(filter).Project(projection).ToList();
  1. $cursor = $db->coll("inventory")->find(
  2. { status => "A" }, { projection => { "size.uom" => 0 } }
  3. );
  1. client[:inventory].find({ status: 'A' },
  2. projection: { 'size.uom' => 0 })
  1. findObservable = collection.find(equal("status", "A")).projection(exclude("size.uom"))
  1. projection := bson.D{
  2. {"size.uom", 0},
  3. }
  4.  
  5. cursor, err := coll.Find(
  6. context.Background(),
  7. bson.D{
  8. {"status", "A"},
  9. },
  10. options.Find().SetProjection(projection),
  11. )

Projection on Embedded Documents in an Array

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

The following example specifies a projection to return:

  • The _id field (returned by default),
  • The item field,
  • The status field,
  • The qty field in the documents embedded in the instock array.
  • Mongo Shell
  • Compass
  • Python
  • Java (Sync)
  • Node.js
  • Other
    • PHP
    • Motor
    • Java (Async)
    • C#
    • Perl
    • Ruby
    • Scala
    • Go
  1. db.inventory.find( { status: "A" }, { item: 1, status: 1, "instock.qty": 1 } )

Copy the following expression into the Filter bar:

  1. { status: "A" }

Copy the following expression into the Projectbar:

  1. { item: 1, status: 1, "instock.qty": 1 }

Click Find.

../../_images/compass-project-embedded-array-docs.png

  1. cursor = db.inventory.find(
  2. {"status": "A"}, {"item": 1, "status": 1, "instock.qty": 1})

To specify a projection document, chain thecom.mongodb.client.FindIterable.projection method to thefind method. The example uses thecom.mongodb.client.model.Projections class to create theprojection documents.

  1. findIterable = collection.find(eq("status", "A")).projection(include("item", "status", "instock.qty"));
  1. const cursor = db
  2. .collection('inventory')
  3. .find({
  4. status: 'A'
  5. })
  6. .project({ item: 1, status: 1, 'instock.qty': 1 });
  1. $cursor = $db->inventory->find(
  2. ['status' => 'A'],
  3. ['projection' => ['item' => 1, 'status' => 1, 'instock.qty' => 1]]
  4. );
  1. cursor = db.inventory.find(
  2. {"status": "A"}, {"item": 1, "status": 1, "instock.qty": 1})
  1. findPublisher = collection.find(eq("status", "A")).projection(include("item", "status", "instock.qty"));
  1. var filter = Builders<BsonDocument>.Filter.Eq("status", "A");
  2. var projection = Builders<BsonDocument>.Projection.Include("item").Include("status").Include("instock.qty");
  3. var result = collection.Find<BsonDocument>(filter).Project(projection).ToList();
  1. $cursor = $db->coll("inventory")->find( { status => "A" },
  2. { projection => { item => 1, status => 1, "instock.qty" => 1 } } );
  1. client[:inventory].find({ status: 'A' },
  2. projection: {'item' => 1, 'status' => 1, 'instock.qty' => 1 })
  1. findObservable = collection.find(equal("status", "A")).projection(include("item", "status", "instock.qty"))
  1. projection := bson.D{
  2. {"item", 1},
  3. {"status", 1},
  4. {"instock.qty", 1},
  5. }
  6.  
  7. cursor, err := coll.Find(
  8. context.Background(),
  9. bson.D{
  10. {"status", "A"},
  11. },
  12. options.Find().SetProjection(projection),
  13. )

Project Specific Array Elements in the Returned Array

  • Mongo Shell
  • Compass
  • Python
  • Java (Sync)
  • Node.js
  • Other
    • PHP
    • Java (Async)
    • C#
    • Perl
    • Ruby
    • Scala
    • Go

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

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

  • Mongo Shell
  • Python
  • Java (Sync)
  • Node.js
  • PHP
  • Other
    • Motor
    • Java (Async)
    • C#
    • Perl
    • Ruby
    • Scala
    • Go
  1. db.inventory.find( { status: "A" }, { item: 1, status: 1, instock: { $slice: -1 } } )
  1. cursor = db.inventory.find(
  2. {"status": "A"},
  3. {"item": 1, "status": 1, "instock": {"$slice": -1}})

To specify a projection document, chain thecom.mongodb.client.FindIterable.projection method to thefind method. The example uses thecom.mongodb.client.model.Projections class to create theprojection documents.

  1. findIterable = collection.find(eq("status", "A"))
  2. .projection(fields(include("item", "status"), slice("instock", -1)));
  1. const cursor = db
  2. .collection('inventory')
  3. .find({
  4. status: 'A'
  5. })
  6. .project({ item: 1, status: 1, instock: { $slice: -1 } });
  1. $cursor = $db->inventory->find(
  2. ['status' => 'A'],
  3. ['projection' => ['item' => 1, 'status' => 1, 'instock' => ['$slice' => -1]]]
  4. );
  1. cursor = db.inventory.find(
  2. {"status": "A"},
  3. {"item": 1, "status": 1, "instock": {"$slice": -1}})
  1. findPublisher = collection.find(eq("status", "A"))
  2. .projection(fields(include("item", "status"), slice("instock", -1)));
  1. var filter = Builders<BsonDocument>.Filter.Eq("status", "A");
  2. var projection = Builders<BsonDocument>.Projection.Include("item").Include("status").Slice("instock", -1);
  3. var result = collection.Find<BsonDocument>(filter).Project(projection).ToList();
  1. $cursor = $db->coll("inventory")->find(
  2. { status => "A" },
  3. { projection => { item => 1, status => 1, instock => { '$slice' => -1 } } }
  4. );
  1. client[:inventory].find({ status: 'A' },
  2. projection: {'item' => 1,
  3. 'status' => 1,
  4. 'instock' => { '$slice' => -1 } })
  1. findObservable = collection.find(equal("status", "A"))
  2. .projection(fields(include("item", "status"), slice("instock", -1)))
  1. projection := bson.D{
  2. {"item", 1},
  3. {"status", 1},
  4. {"instock", bson.D{
  5. {"$slice", -1},
  6. }},
  7. }
  8.  
  9. cursor, err := coll.Find(
  10. context.Background(),
  11. bson.D{
  12. {"status", "A"},
  13. },
  14. options.Find().SetProjection(projection),
  15. )

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

Currently, MongoDB Compass does not support any methods forprojecting specific array elements in a returned array.

For additional details and examples on projection in MongoDBCompass, refer to the CompassQuery Bar documentation.

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

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

  • Mongo Shell
  • Python
  • Java (Sync)
  • Node.js
  • PHP
  • Other
    • Motor
    • Java (Async)
    • C#
    • Perl
    • Ruby
    • Scala
    • Go
  1. db.inventory.find( { status: "A" }, { item: 1, status: 1, instock: { $slice: -1 } } )
  1. cursor = db.inventory.find(
  2. {"status": "A"},
  3. {"item": 1, "status": 1, "instock": {"$slice": -1}})

To specify a projection document, chain thecom.mongodb.client.FindIterable.projection method to thefind method. The example uses thecom.mongodb.client.model.Projections class to create theprojection documents.

  1. findIterable = collection.find(eq("status", "A"))
  2. .projection(fields(include("item", "status"), slice("instock", -1)));
  1. const cursor = db
  2. .collection('inventory')
  3. .find({
  4. status: 'A'
  5. })
  6. .project({ item: 1, status: 1, instock: { $slice: -1 } });
  1. $cursor = $db->inventory->find(
  2. ['status' => 'A'],
  3. ['projection' => ['item' => 1, 'status' => 1, 'instock' => ['$slice' => -1]]]
  4. );
  1. cursor = db.inventory.find(
  2. {"status": "A"},
  3. {"item": 1, "status": 1, "instock": {"$slice": -1}})
  1. findPublisher = collection.find(eq("status", "A"))
  2. .projection(fields(include("item", "status"), slice("instock", -1)));
  1. var filter = Builders<BsonDocument>.Filter.Eq("status", "A");
  2. var projection = Builders<BsonDocument>.Projection.Include("item").Include("status").Slice("instock", -1);
  3. var result = collection.Find<BsonDocument>(filter).Project(projection).ToList();
  1. $cursor = $db->coll("inventory")->find(
  2. { status => "A" },
  3. { projection => { item => 1, status => 1, instock => { '$slice' => -1 } } }
  4. );
  1. client[:inventory].find({ status: 'A' },
  2. projection: {'item' => 1,
  3. 'status' => 1,
  4. 'instock' => { '$slice' => -1 } })
  1. findObservable = collection.find(equal("status", "A"))
  2. .projection(fields(include("item", "status"), slice("instock", -1)))
  1. projection := bson.D{
  2. {"item", 1},
  3. {"status", 1},
  4. {"instock", bson.D{
  5. {"$slice", -1},
  6. }},
  7. }
  8.  
  9. cursor, err := coll.Find(
  10. context.Background(),
  11. bson.D{
  12. {"status", "A"},
  13. },
  14. options.Find().SetProjection(projection),
  15. )

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

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

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

  • Mongo Shell
  • Python
  • Java (Sync)
  • Node.js
  • PHP
  • Other
    • Motor
    • Java (Async)
    • C#
    • Perl
    • Ruby
    • Scala
    • Go
  1. db.inventory.find( { status: "A" }, { item: 1, status: 1, instock: { $slice: -1 } } )
  1. cursor = db.inventory.find(
  2. {"status": "A"},
  3. {"item": 1, "status": 1, "instock": {"$slice": -1}})

To specify a projection document, chain thecom.mongodb.client.FindIterable.projection method to thefind method. The example uses thecom.mongodb.client.model.Projections class to create theprojection documents.

  1. findIterable = collection.find(eq("status", "A"))
  2. .projection(fields(include("item", "status"), slice("instock", -1)));
  1. const cursor = db
  2. .collection('inventory')
  3. .find({
  4. status: 'A'
  5. })
  6. .project({ item: 1, status: 1, instock: { $slice: -1 } });
  1. $cursor = $db->inventory->find(
  2. ['status' => 'A'],
  3. ['projection' => ['item' => 1, 'status' => 1, 'instock' => ['$slice' => -1]]]
  4. );
  1. cursor = db.inventory.find(
  2. {"status": "A"},
  3. {"item": 1, "status": 1, "instock": {"$slice": -1}})
  1. findPublisher = collection.find(eq("status", "A"))
  2. .projection(fields(include("item", "status"), slice("instock", -1)));
  1. var filter = Builders<BsonDocument>.Filter.Eq("status", "A");
  2. var projection = Builders<BsonDocument>.Projection.Include("item").Include("status").Slice("instock", -1);
  3. var result = collection.Find<BsonDocument>(filter).Project(projection).ToList();
  1. $cursor = $db->coll("inventory")->find(
  2. { status => "A" },
  3. { projection => { item => 1, status => 1, instock => { '$slice' => -1 } } }
  4. );
  1. client[:inventory].find({ status: 'A' },
  2. projection: {'item' => 1,
  3. 'status' => 1,
  4. 'instock' => { '$slice' => -1 } })
  1. findObservable = collection.find(equal("status", "A"))
  2. .projection(fields(include("item", "status"), slice("instock", -1)))
  1. projection := bson.D{
  2. {"item", 1},
  3. {"status", 1},
  4. {"instock", bson.D{
  5. {"$slice", -1},
  6. }},
  7. }
  8.  
  9. cursor, err := coll.Find(
  10. context.Background(),
  11. bson.D{
  12. {"status", "A"},
  13. },
  14. options.Find().SetProjection(projection),
  15. )

$elemMatch, $slice, and$ are the only way to project specific elementsto include in the returned array. For instance, you cannot_project specific array elements using the array index; e.g.include("instock.0") projection will _not project the arraywith the first element.

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

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

  • Mongo Shell
  • Python
  • Java (Sync)
  • Node.js
  • PHP
  • Other
    • Motor
    • Java (Async)
    • C#
    • Perl
    • Ruby
    • Scala
    • Go
  1. db.inventory.find( { status: "A" }, { item: 1, status: 1, instock: { $slice: -1 } } )
  1. cursor = db.inventory.find(
  2. {"status": "A"},
  3. {"item": 1, "status": 1, "instock": {"$slice": -1}})

To specify a projection document, chain thecom.mongodb.client.FindIterable.projection method to thefind method. The example uses thecom.mongodb.client.model.Projections class to create theprojection documents.

  1. findIterable = collection.find(eq("status", "A"))
  2. .projection(fields(include("item", "status"), slice("instock", -1)));
  1. const cursor = db
  2. .collection('inventory')
  3. .find({
  4. status: 'A'
  5. })
  6. .project({ item: 1, status: 1, instock: { $slice: -1 } });
  1. $cursor = $db->inventory->find(
  2. ['status' => 'A'],
  3. ['projection' => ['item' => 1, 'status' => 1, 'instock' => ['$slice' => -1]]]
  4. );
  1. cursor = db.inventory.find(
  2. {"status": "A"},
  3. {"item": 1, "status": 1, "instock": {"$slice": -1}})
  1. findPublisher = collection.find(eq("status", "A"))
  2. .projection(fields(include("item", "status"), slice("instock", -1)));
  1. var filter = Builders<BsonDocument>.Filter.Eq("status", "A");
  2. var projection = Builders<BsonDocument>.Projection.Include("item").Include("status").Slice("instock", -1);
  3. var result = collection.Find<BsonDocument>(filter).Project(projection).ToList();
  1. $cursor = $db->coll("inventory")->find(
  2. { status => "A" },
  3. { projection => { item => 1, status => 1, instock => { '$slice' => -1 } } }
  4. );
  1. client[:inventory].find({ status: 'A' },
  2. projection: {'item' => 1,
  3. 'status' => 1,
  4. 'instock' => { '$slice' => -1 } })
  1. findObservable = collection.find(equal("status", "A"))
  2. .projection(fields(include("item", "status"), slice("instock", -1)))
  1. projection := bson.D{
  2. {"item", 1},
  3. {"status", 1},
  4. {"instock", bson.D{
  5. {"$slice", -1},
  6. }},
  7. }
  8.  
  9. cursor, err := coll.Find(
  10. context.Background(),
  11. bson.D{
  12. {"status", "A"},
  13. },
  14. options.Find().SetProjection(projection),
  15. )

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

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

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

  • Mongo Shell
  • Python
  • Java (Sync)
  • Node.js
  • PHP
  • Other
    • Motor
    • Java (Async)
    • C#
    • Perl
    • Ruby
    • Scala
    • Go
  1. db.inventory.find( { status: "A" }, { item: 1, status: 1, instock: { $slice: -1 } } )
  1. cursor = db.inventory.find(
  2. {"status": "A"},
  3. {"item": 1, "status": 1, "instock": {"$slice": -1}})

To specify a projection document, chain thecom.mongodb.client.FindIterable.projection method to thefind method. The example uses thecom.mongodb.client.model.Projections class to create theprojection documents.

  1. findIterable = collection.find(eq("status", "A"))
  2. .projection(fields(include("item", "status"), slice("instock", -1)));
  1. const cursor = db
  2. .collection('inventory')
  3. .find({
  4. status: 'A'
  5. })
  6. .project({ item: 1, status: 1, instock: { $slice: -1 } });
  1. $cursor = $db->inventory->find(
  2. ['status' => 'A'],
  3. ['projection' => ['item' => 1, 'status' => 1, 'instock' => ['$slice' => -1]]]
  4. );
  1. cursor = db.inventory.find(
  2. {"status": "A"},
  3. {"item": 1, "status": 1, "instock": {"$slice": -1}})
  1. findPublisher = collection.find(eq("status", "A"))
  2. .projection(fields(include("item", "status"), slice("instock", -1)));
  1. var filter = Builders<BsonDocument>.Filter.Eq("status", "A");
  2. var projection = Builders<BsonDocument>.Projection.Include("item").Include("status").Slice("instock", -1);
  3. var result = collection.Find<BsonDocument>(filter).Project(projection).ToList();
  1. $cursor = $db->coll("inventory")->find(
  2. { status => "A" },
  3. { projection => { item => 1, status => 1, instock => { '$slice' => -1 } } }
  4. );
  1. client[:inventory].find({ status: 'A' },
  2. projection: {'item' => 1,
  3. 'status' => 1,
  4. 'instock' => { '$slice' => -1 } })
  1. findObservable = collection.find(equal("status", "A"))
  2. .projection(fields(include("item", "status"), slice("instock", -1)))
  1. projection := bson.D{
  2. {"item", 1},
  3. {"status", 1},
  4. {"instock", bson.D{
  5. {"$slice", -1},
  6. }},
  7. }
  8.  
  9. cursor, err := coll.Find(
  10. context.Background(),
  11. bson.D{
  12. {"status", "A"},
  13. },
  14. options.Find().SetProjection(projection),
  15. )

$elemMatch, $slice, and$ are the only way to project specific elementsto include in the returned array. For instance, you cannot_project specific array elements using the array index; e.g.[ "instock.0" => 1 ] projection will _not project the arraywith the first element.

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

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

  • Mongo Shell
  • Python
  • Java (Sync)
  • Node.js
  • PHP
  • Other
    • Motor
    • Java (Async)
    • C#
    • Perl
    • Ruby
    • Scala
    • Go
  1. db.inventory.find( { status: "A" }, { item: 1, status: 1, instock: { $slice: -1 } } )
  1. cursor = db.inventory.find(
  2. {"status": "A"},
  3. {"item": 1, "status": 1, "instock": {"$slice": -1}})

To specify a projection document, chain thecom.mongodb.client.FindIterable.projection method to thefind method. The example uses thecom.mongodb.client.model.Projections class to create theprojection documents.

  1. findIterable = collection.find(eq("status", "A"))
  2. .projection(fields(include("item", "status"), slice("instock", -1)));
  1. const cursor = db
  2. .collection('inventory')
  3. .find({
  4. status: 'A'
  5. })
  6. .project({ item: 1, status: 1, instock: { $slice: -1 } });
  1. $cursor = $db->inventory->find(
  2. ['status' => 'A'],
  3. ['projection' => ['item' => 1, 'status' => 1, 'instock' => ['$slice' => -1]]]
  4. );
  1. cursor = db.inventory.find(
  2. {"status": "A"},
  3. {"item": 1, "status": 1, "instock": {"$slice": -1}})
  1. findPublisher = collection.find(eq("status", "A"))
  2. .projection(fields(include("item", "status"), slice("instock", -1)));
  1. var filter = Builders<BsonDocument>.Filter.Eq("status", "A");
  2. var projection = Builders<BsonDocument>.Projection.Include("item").Include("status").Slice("instock", -1);
  3. var result = collection.Find<BsonDocument>(filter).Project(projection).ToList();
  1. $cursor = $db->coll("inventory")->find(
  2. { status => "A" },
  3. { projection => { item => 1, status => 1, instock => { '$slice' => -1 } } }
  4. );
  1. client[:inventory].find({ status: 'A' },
  2. projection: {'item' => 1,
  3. 'status' => 1,
  4. 'instock' => { '$slice' => -1 } })
  1. findObservable = collection.find(equal("status", "A"))
  2. .projection(fields(include("item", "status"), slice("instock", -1)))
  1. projection := bson.D{
  2. {"item", 1},
  3. {"status", 1},
  4. {"instock", bson.D{
  5. {"$slice", -1},
  6. }},
  7. }
  8.  
  9. cursor, err := coll.Find(
  10. context.Background(),
  11. bson.D{
  12. {"status", "A"},
  13. },
  14. options.Find().SetProjection(projection),
  15. )

$elemMatch, $slice, and$ are the only way to project specific elementsto include in the returned array. For instance, you cannot_project specific array elements using the array index; e.g.include("instock.0") projection will _not project the arraywith the first element.

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

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

  • Mongo Shell
  • Python
  • Java (Sync)
  • Node.js
  • PHP
  • Other
    • Motor
    • Java (Async)
    • C#
    • Perl
    • Ruby
    • Scala
    • Go
  1. db.inventory.find( { status: "A" }, { item: 1, status: 1, instock: { $slice: -1 } } )
  1. cursor = db.inventory.find(
  2. {"status": "A"},
  3. {"item": 1, "status": 1, "instock": {"$slice": -1}})

To specify a projection document, chain thecom.mongodb.client.FindIterable.projection method to thefind method. The example uses thecom.mongodb.client.model.Projections class to create theprojection documents.

  1. findIterable = collection.find(eq("status", "A"))
  2. .projection(fields(include("item", "status"), slice("instock", -1)));
  1. const cursor = db
  2. .collection('inventory')
  3. .find({
  4. status: 'A'
  5. })
  6. .project({ item: 1, status: 1, instock: { $slice: -1 } });
  1. $cursor = $db->inventory->find(
  2. ['status' => 'A'],
  3. ['projection' => ['item' => 1, 'status' => 1, 'instock' => ['$slice' => -1]]]
  4. );
  1. cursor = db.inventory.find(
  2. {"status": "A"},
  3. {"item": 1, "status": 1, "instock": {"$slice": -1}})
  1. findPublisher = collection.find(eq("status", "A"))
  2. .projection(fields(include("item", "status"), slice("instock", -1)));
  1. var filter = Builders<BsonDocument>.Filter.Eq("status", "A");
  2. var projection = Builders<BsonDocument>.Projection.Include("item").Include("status").Slice("instock", -1);
  3. var result = collection.Find<BsonDocument>(filter).Project(projection).ToList();
  1. $cursor = $db->coll("inventory")->find(
  2. { status => "A" },
  3. { projection => { item => 1, status => 1, instock => { '$slice' => -1 } } }
  4. );
  1. client[:inventory].find({ status: 'A' },
  2. projection: {'item' => 1,
  3. 'status' => 1,
  4. 'instock' => { '$slice' => -1 } })
  1. findObservable = collection.find(equal("status", "A"))
  2. .projection(fields(include("item", "status"), slice("instock", -1)))
  1. projection := bson.D{
  2. {"item", 1},
  3. {"status", 1},
  4. {"instock", bson.D{
  5. {"$slice", -1},
  6. }},
  7. }
  8.  
  9. cursor, err := coll.Find(
  10. context.Background(),
  11. bson.D{
  12. {"status", "A"},
  13. },
  14. options.Find().SetProjection(projection),
  15. )

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

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

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

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

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

  • Mongo Shell
  • Python
  • Java (Sync)
  • Node.js
  • PHP
  • Other
    • Motor
    • Java (Async)
    • C#
    • Perl
    • Ruby
    • Scala
    • Go
  1. db.inventory.find( { status: "A" }, { item: 1, status: 1, instock: { $slice: -1 } } )
  1. cursor = db.inventory.find(
  2. {"status": "A"},
  3. {"item": 1, "status": 1, "instock": {"$slice": -1}})

To specify a projection document, chain thecom.mongodb.client.FindIterable.projection method to thefind method. The example uses thecom.mongodb.client.model.Projections class to create theprojection documents.

  1. findIterable = collection.find(eq("status", "A"))
  2. .projection(fields(include("item", "status"), slice("instock", -1)));
  1. const cursor = db
  2. .collection('inventory')
  3. .find({
  4. status: 'A'
  5. })
  6. .project({ item: 1, status: 1, instock: { $slice: -1 } });
  1. $cursor = $db->inventory->find(
  2. ['status' => 'A'],
  3. ['projection' => ['item' => 1, 'status' => 1, 'instock' => ['$slice' => -1]]]
  4. );
  1. cursor = db.inventory.find(
  2. {"status": "A"},
  3. {"item": 1, "status": 1, "instock": {"$slice": -1}})
  1. findPublisher = collection.find(eq("status", "A"))
  2. .projection(fields(include("item", "status"), slice("instock", -1)));
  1. var filter = Builders<BsonDocument>.Filter.Eq("status", "A");
  2. var projection = Builders<BsonDocument>.Projection.Include("item").Include("status").Slice("instock", -1);
  3. var result = collection.Find<BsonDocument>(filter).Project(projection).ToList();
  1. $cursor = $db->coll("inventory")->find(
  2. { status => "A" },
  3. { projection => { item => 1, status => 1, instock => { '$slice' => -1 } } }
  4. );
  1. client[:inventory].find({ status: 'A' },
  2. projection: {'item' => 1,
  3. 'status' => 1,
  4. 'instock' => { '$slice' => -1 } })
  1. findObservable = collection.find(equal("status", "A"))
  2. .projection(fields(include("item", "status"), slice("instock", -1)))
  1. projection := bson.D{
  2. {"item", 1},
  3. {"status", 1},
  4. {"instock", bson.D{
  5. {"$slice", -1},
  6. }},
  7. }
  8.  
  9. cursor, err := coll.Find(
  10. context.Background(),
  11. bson.D{
  12. {"status", "A"},
  13. },
  14. options.Find().SetProjection(projection),
  15. )

$elemMatch, $slice, and$ are the only way to project specific elementsto include in the returned array. For instance, you cannot_project specific array elements using the array index; e.g.{ "instock.0" => 1 } projection will _not project the arraywith the first element.

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

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

  • Mongo Shell
  • Python
  • Java (Sync)
  • Node.js
  • PHP
  • Other
    • Motor
    • Java (Async)
    • C#
    • Perl
    • Ruby
    • Scala
    • Go
  1. db.inventory.find( { status: "A" }, { item: 1, status: 1, instock: { $slice: -1 } } )
  1. cursor = db.inventory.find(
  2. {"status": "A"},
  3. {"item": 1, "status": 1, "instock": {"$slice": -1}})

To specify a projection document, chain thecom.mongodb.client.FindIterable.projection method to thefind method. The example uses thecom.mongodb.client.model.Projections class to create theprojection documents.

  1. findIterable = collection.find(eq("status", "A"))
  2. .projection(fields(include("item", "status"), slice("instock", -1)));
  1. const cursor = db
  2. .collection('inventory')
  3. .find({
  4. status: 'A'
  5. })
  6. .project({ item: 1, status: 1, instock: { $slice: -1 } });
  1. $cursor = $db->inventory->find(
  2. ['status' => 'A'],
  3. ['projection' => ['item' => 1, 'status' => 1, 'instock' => ['$slice' => -1]]]
  4. );
  1. cursor = db.inventory.find(
  2. {"status": "A"},
  3. {"item": 1, "status": 1, "instock": {"$slice": -1}})
  1. findPublisher = collection.find(eq("status", "A"))
  2. .projection(fields(include("item", "status"), slice("instock", -1)));
  1. var filter = Builders<BsonDocument>.Filter.Eq("status", "A");
  2. var projection = Builders<BsonDocument>.Projection.Include("item").Include("status").Slice("instock", -1);
  3. var result = collection.Find<BsonDocument>(filter).Project(projection).ToList();
  1. $cursor = $db->coll("inventory")->find(
  2. { status => "A" },
  3. { projection => { item => 1, status => 1, instock => { '$slice' => -1 } } }
  4. );
  1. client[:inventory].find({ status: 'A' },
  2. projection: {'item' => 1,
  3. 'status' => 1,
  4. 'instock' => { '$slice' => -1 } })
  1. findObservable = collection.find(equal("status", "A"))
  2. .projection(fields(include("item", "status"), slice("instock", -1)))
  1. projection := bson.D{
  2. {"item", 1},
  3. {"status", 1},
  4. {"instock", bson.D{
  5. {"$slice", -1},
  6. }},
  7. }
  8.  
  9. cursor, err := coll.Find(
  10. context.Background(),
  11. bson.D{
  12. {"status", "A"},
  13. },
  14. options.Find().SetProjection(projection),
  15. )

$elemMatch, $slice, and$ are the only way to project specific elementsto include in the returned array. For instance, you cannot_project specific array elements using the array index; e.g.{ "instock.0" => 1 } projection will _not project the arraywith the first element.

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

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

  • Mongo Shell
  • Python
  • Java (Sync)
  • Node.js
  • PHP
  • Other
    • Motor
    • Java (Async)
    • C#
    • Perl
    • Ruby
    • Scala
    • Go
  1. db.inventory.find( { status: "A" }, { item: 1, status: 1, instock: { $slice: -1 } } )
  1. cursor = db.inventory.find(
  2. {"status": "A"},
  3. {"item": 1, "status": 1, "instock": {"$slice": -1}})

To specify a projection document, chain thecom.mongodb.client.FindIterable.projection method to thefind method. The example uses thecom.mongodb.client.model.Projections class to create theprojection documents.

  1. findIterable = collection.find(eq("status", "A"))
  2. .projection(fields(include("item", "status"), slice("instock", -1)));
  1. const cursor = db
  2. .collection('inventory')
  3. .find({
  4. status: 'A'
  5. })
  6. .project({ item: 1, status: 1, instock: { $slice: -1 } });
  1. $cursor = $db->inventory->find(
  2. ['status' => 'A'],
  3. ['projection' => ['item' => 1, 'status' => 1, 'instock' => ['$slice' => -1]]]
  4. );
  1. cursor = db.inventory.find(
  2. {"status": "A"},
  3. {"item": 1, "status": 1, "instock": {"$slice": -1}})
  1. findPublisher = collection.find(eq("status", "A"))
  2. .projection(fields(include("item", "status"), slice("instock", -1)));
  1. var filter = Builders<BsonDocument>.Filter.Eq("status", "A");
  2. var projection = Builders<BsonDocument>.Projection.Include("item").Include("status").Slice("instock", -1);
  3. var result = collection.Find<BsonDocument>(filter).Project(projection).ToList();
  1. $cursor = $db->coll("inventory")->find(
  2. { status => "A" },
  3. { projection => { item => 1, status => 1, instock => { '$slice' => -1 } } }
  4. );
  1. client[:inventory].find({ status: 'A' },
  2. projection: {'item' => 1,
  3. 'status' => 1,
  4. 'instock' => { '$slice' => -1 } })
  1. findObservable = collection.find(equal("status", "A"))
  2. .projection(fields(include("item", "status"), slice("instock", -1)))
  1. projection := bson.D{
  2. {"item", 1},
  3. {"status", 1},
  4. {"instock", bson.D{
  5. {"$slice", -1},
  6. }},
  7. }
  8.  
  9. cursor, err := coll.Find(
  10. context.Background(),
  11. bson.D{
  12. {"status", "A"},
  13. },
  14. options.Find().SetProjection(projection),
  15. )

$elemMatch, $slice, and$ are the only way to project specific elementsto include in the returned array. For instance, you cannot_project specific array elements using the array index; e.g.include("instock.0") projection will _not project the arraywith the first element.

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

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

  • Mongo Shell
  • Python
  • Java (Sync)
  • Node.js
  • PHP
  • Other
    • Motor
    • Java (Async)
    • C#
    • Perl
    • Ruby
    • Scala
    • Go
  1. db.inventory.find( { status: "A" }, { item: 1, status: 1, instock: { $slice: -1 } } )
  1. cursor = db.inventory.find(
  2. {"status": "A"},
  3. {"item": 1, "status": 1, "instock": {"$slice": -1}})

To specify a projection document, chain thecom.mongodb.client.FindIterable.projection method to thefind method. The example uses thecom.mongodb.client.model.Projections class to create theprojection documents.

  1. findIterable = collection.find(eq("status", "A"))
  2. .projection(fields(include("item", "status"), slice("instock", -1)));
  1. const cursor = db
  2. .collection('inventory')
  3. .find({
  4. status: 'A'
  5. })
  6. .project({ item: 1, status: 1, instock: { $slice: -1 } });
  1. $cursor = $db->inventory->find(
  2. ['status' => 'A'],
  3. ['projection' => ['item' => 1, 'status' => 1, 'instock' => ['$slice' => -1]]]
  4. );
  1. cursor = db.inventory.find(
  2. {"status": "A"},
  3. {"item": 1, "status": 1, "instock": {"$slice": -1}})
  1. findPublisher = collection.find(eq("status", "A"))
  2. .projection(fields(include("item", "status"), slice("instock", -1)));
  1. var filter = Builders<BsonDocument>.Filter.Eq("status", "A");
  2. var projection = Builders<BsonDocument>.Projection.Include("item").Include("status").Slice("instock", -1);
  3. var result = collection.Find<BsonDocument>(filter).Project(projection).ToList();
  1. $cursor = $db->coll("inventory")->find(
  2. { status => "A" },
  3. { projection => { item => 1, status => 1, instock => { '$slice' => -1 } } }
  4. );
  1. client[:inventory].find({ status: 'A' },
  2. projection: {'item' => 1,
  3. 'status' => 1,
  4. 'instock' => { '$slice' => -1 } })
  1. findObservable = collection.find(equal("status", "A"))
  2. .projection(fields(include("item", "status"), slice("instock", -1)))
  1. projection := bson.D{
  2. {"item", 1},
  3. {"status", 1},
  4. {"instock", bson.D{
  5. {"$slice", -1},
  6. }},
  7. }
  8.  
  9. cursor, err := coll.Find(
  10. context.Background(),
  11. bson.D{
  12. {"status", "A"},
  13. },
  14. options.Find().SetProjection(projection),
  15. )

$elemMatch, $slice, and$ are the only way to project specific elementsto include in the returned array. For instance, you cannot_project specific array elements using the array index; e.g.include("instock.0") projection will _not project the arraywith the first element.

See also

Query Documents