Display the undefined and exact MongoDB document records

To display undefined and exact MongoDB document records, use the forEach() method with printjson(). The forEach() callback accepts two parameters: the document and the index, allowing you to display either the actual documents or undefined values.

Syntax

db.collection.find({}).forEach((document, index) => {
    printjson(document);  // Display documents
    printjson(index);     // Display undefined
});

Sample Data

db.demo496.insertMany([
    { "Name": "David", "CountryName": "US" },
    { "Name": "John", "CountryName": "AUS" },
    { "Name": "Robert", "CountryName": "UK" }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e84b04ab0f3fa88e22790ce"),
        ObjectId("5e84b054b0f3fa88e22790cf"),
        ObjectId("5e84b05db0f3fa88e22790d0")
    ]
}

Display All Documents

db.demo496.find();
{ "_id": ObjectId("5e84b04ab0f3fa88e22790ce"), "Name": "David", "CountryName": "US" }
{ "_id": ObjectId("5e84b054b0f3fa88e22790cf"), "Name": "John", "CountryName": "AUS" }
{ "_id": ObjectId("5e84b05db0f3fa88e22790d0"), "Name": "Robert", "CountryName": "UK" }

Method 1: Display Undefined Values

Using the second parameter (index) in forEach() displays undefined ?

db.demo496.find({}).forEach((done, notDone) => {
    printjson(notDone);
});
undefined
undefined
undefined

Method 2: Display Exact Documents

Using the first parameter displays the actual document records ?

db.demo496.find({}).forEach((done, notDone) => {
    printjson(done);
});
{
    "_id": ObjectId("5e84b04ab0f3fa88e22790ce"),
    "Name": "David",
    "CountryName": "US"
}
{
    "_id": ObjectId("5e84b054b0f3fa88e22790cf"),
    "Name": "John",
    "CountryName": "AUS"
}
{
    "_id": ObjectId("5e84b05db0f3fa88e22790d0"),
    "Name": "Robert",
    "CountryName": "UK"
}

Conclusion

The forEach() method's callback parameters determine the output: the first parameter returns document data while the second parameter returns undefined. Use printjson() to format the output properly.

Updated on: 2026-03-15T03:17:50+05:30

358 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements