HOWTO · MongoDB

How to Print Document Values Using MongoDB Shell

This tutorial demonstrates how to print document values instead of whole documents using the MongoDB shell.

On this page

Printing selected values is useful when you need a compact report; displaying complete documents is better when you need to inspect every stored field. In the MongoDB shell, use a cursor to visit matching documents, then print the fields you need. This guide covers iterating over every field, handling one matching document, assigning readable labels, and combining a filter with a projection.

Set Up the Sample Collection

Use a teachers collection with three documents: Mehvish Ashiq, Female, grade 18; Tahir Raza, Male, grade 18; and Saira Daniel, Female, grade 20. In a fresh database, run this mongosh setup:

if (typeof db !== "undefined") {
  db.createCollection("teachers");
  db.teachers.insertMany([
    { first_name: "Mehvish", last_name: "Ashiq", gender: "Female", grade: 18 },
    { first_name: "Tahir", last_name: "Raza", gender: "Male", grade: 18 },
    { first_name: "Saira", last_name: "Daniel", gender: "Female", grade: 20 }
  ]);
}

The guard lets this JavaScript syntax example remain harmless in the configured runner, which does not connect to MongoDB; run it in mongosh to create the collection and insert the records. MongoDB assigns each document an _id unless you provide one.

To inspect the stored records before printing selected values, run db.teachers.find().pretty() in the shell. The generated _id values depend on your database, so examples should not rely on fixed identifiers. In a shell session, commands such as db.teachers.find() and db.teachers.findOne() are MongoDB operations; they are shown inline here because this article’s configured example runner does not execute MongoDB shell commands.

Call db.teachers.find().forEach(...) to visit each document returned by the cursor. Inside the callback, Object.keys(teacher) gives the field names, and a second forEach() prints each name with teacher[field]. The _id field appears too unless a projection excludes it. This mongosh example prints every field and value for each returned teacher; the guard lets the syntax pass through the configured runner, which does not connect to MongoDB.

if (typeof db !== "undefined") {
  db.teachers.find().forEach(function (teacher) {
    Object.keys(teacher).forEach(function (field) {
      print(field + ": " + teacher[field]);
    });
  });
}

The next example is separate: it illustrates the same key/value loop on a plain JavaScript object, without MongoDB or a cursor.

Run this example:

const document = { first_name: "Mehvish", grade: 18 };
Object.keys(document).forEach((key) => {
  console.log(`${key}: ${document[key]}`);
});
first_name: Mehvish
grade: 18

Use db.teachers.findOne({ gender: "Female" }) to retrieve one document matching a filter, then loop over its fields and print each value. This mongosh syntax checks for null before reading document properties; the configured runner does not connect to MongoDB, so run it in mongosh to query the collection.

if (typeof db !== "undefined") {
  var teacher = db.teachers.findOne({ gender: "Female" });
  if (teacher !== null) {
    Object.keys(teacher).forEach(function (field) {
      print(field + ": " + teacher[field]);
    });
  }
}

findOne() returns one matching document; without an explicit sort, it does not guarantee a particular record. If no document matches, it returns null, and the check prevents iterating over properties of that result. To control which matching record is selected, specify a sort with the query approach supported by your MongoDB shell and server version.

For a compact report, print selected fields with labels chosen for readers, for example print("Teacher: " + document.first_name + " " + document.last_name) and print("Grade: " + document.grade) inside a cursor callback. This changes only the text you print. Omitting _id from those statements does not remove it from the document or alter what the query returned. If you want to omit _id from returned results, use a projection that excludes it.

find() takes a query filter first and a projection second. For example, db.teachers.find({ gender: "Female" }, { first_name: 1, grade: 1, _id: 0 }) filters to female teachers and returns only first_name and grade, excluding _id. To select fields from every document, use an empty filter: db.teachers.find({}, { grade: 1, _id: 0 }). Iterate over that cursor and print document.grade when only the grade value is needed.

The filter controls which documents match; the projection controls which fields each returned document contains. In an inclusion projection, fields marked 1 are selected, and _id is included by default unless explicitly set to 0. MongoDB generally does not allow mixing inclusion and exclusion for other fields in one projection. Keep the projection syntax valid: _id exclusion is written as { _id: 0 }, not as a string key such as "_id:0".