Read a collection
suggest changeGet 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 |
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents