Read a collection

suggest change

Get all documents in the collection myCollection and print them. This uses the MongoDB Node driver 4 or later. MongoClient.connect(url, callback) no longer passes the database object, and cursor.each has been removed.

const { MongoClient } = require('mongodb');

const url = 'mongodb://localhost:27017';

async function main() {
  const client = new MongoClient(url);
  await client.connect();
  try {
    const docs = await client.db('test').collection('myCollection').find().toArray();
    docs.forEach(function (doc) {
      console.log(doc);
    });
  } finally {
    await client.close();
  }
}

main().catch(function (err) {
  console.error(err);
});

Collection method find()

db.collection(collection).find()

Argument Type Description
collection string Name of the collection to read

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents