Chapter Overview
This chapter introduces how to set the return of specified fields in MongoDB queries rather than returning all field data.
Test Data
Insert a few pieces of data into the inventory collection
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 } ] }
]);
Format
{<field>: 1 or 0}
Explanation:
-
- field name - 1 represents return the field, 0 represents exclude the field (i.e., not return)
Tip: Using true/false instead of 1 and 0 is also acceptable.
Return Specified Fields
Set which fields to return via the second parameter of the find function.
db.inventory.find( { status: "A" }, { item: 1, status: 1 } )
Explanation:
- Documents where the status satisfies A are queried.
- Returns the _id, item, and status fields.
Tip: The _id field is returned by default.
Equivalent SQL:
SELECT item, status from inventory WHERE status = "A"
Exclude Specified Fields
db.inventory.find( { status: "A" }, { status: 0, instock: 0 } )
Explanation:
- Documents where the status satisfies A are queried
- Returns all data except the item and status fields.
Return Specified Fields in Nested Documents
db.inventory.find(
{ status: "A" },
{ item: 1, status: 1, "size.uom": 1 }
)
Explanation:
- size.uom represents returning the uom field under size.