In the previous tutorial, Environment Setup, one of the easiest ways to get started with MongoDB, we completed environment setup for MongoDB. *

On server localhost:27017, create a database table named Person under database admin and insert two records:

The two successfully inserted records viewed with MongoDB Compass are shown above.

Now we read the two records using NodeJS.

Start by running NPM install mongodb from the command line.

Then create a new JavaScript file and copy the following:

Note line 12, dbo.collection(” person “).find ({}).toarray, which reads all the records in the table person.

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017";
MongoClient.connect(url, function(err, db) {
    if (err){
        console.log(err);
        throw err;
    }
    console.log("Jerry DB connection established!");
    var dbo = db.db("admin");
    dbo.collection("person"). find({
    }
    ).toArray(function(err, result) {
        if (err)
        throwerr; console.log(result); db.close(); }); db.close(); });Copy the code

If I only want to read the record whose name is Jerry, I simply pass the WHERE condition to find:

From the debugger you can observe that it is read back as expected:

For more of Jerry’s original technical articles, please follow the public account “Wang Zixi” or scan the following QR code: