Notes on getting started with Node and MongoDB

I was pleasantly surprised at how easy it was to set everything up!

First create an account at cloud.mongodb.com

Configure everything in Mongo Atlas

  1. I think the first thing I did was create a cluster (I can't remember if the cluster was already there!)
  2. Create a database:
  3. Choose Database from the left nav
  4. Click Browse Collections
  5. From here you can create a database and add collections to them.
  6. Allow network access:
  7. In the NETWORK ACCESS section I allowed connections from any ip: (0.0.0.0/0)
  8. Create a user:
  9. Click Database Access (in the left nav's SECURITY section)
  10. Click ADD NEW DATABASE USER button
  11. Enter a user name and password
  12. Choose a Built-in Role by selecting Read and write to any database
  13. Click Add User
  14. Click the Database link from the left nav, then click the Connect button.
  15. Click on Drivers
  16. Leave NodeJS selected
  17. Copy the code sample (it includes the connection string to your cluster, you just have to put in the username and password)

Node code to connect to database on Mongo Atlas

Make sure you install the mongodb package (if you don't already have it):

npm i mongodb --save

Here is the sample code that I copied (make sure to use your own user name and password):

const { MongoClient, ServerApiVersion } = require('mongodb');
const uri = "mongodb+srv://<username>:<password>@cluster0.wl25qoo.mongodb.net/?retryWrites=true&w=majority";

// Create a MongoClient with a MongoClientOptions object to set the Stable API version
const client = new MongoClient(uri, {
  serverApi: {
    version: ServerApiVersion.v1,
    strict: true,
    deprecationErrors: true,
  }
});

async function run() {
  try {
    // Connect the client to the server (optional starting in v4.7)
    await client.connect();
    // Send a ping to confirm a successful connection
    await client.db("admin").command({ ping: 1 });
    console.log("Pinged your deployment. You successfully connected to MongoDB!");
  } finally {
    // Ensures that the client will close when you finish/error
    await client.close();
  }
}
run().catch(console.dir);

Then I modified the sample code to include the following samples:


const { MongoClient, ServerApiVersion } = require('mongodb');
const uri = "mongodb+srv://<username>:<password>@cluster0.wl25qoo.mongodb.net/?retryWrites=true&w=majority";


// Create a MongoClient with a MongoClientOptions object to set the Stable API version
const client = new MongoClient(uri, {
  serverApi: {
    version: ServerApiVersion.v1,
    strict: true,
    deprecationErrors: true,
  }
});

async function run() {
  try {
    // Connect the client to the server (optional starting in v4.7)
    await client.connect();
    
    // Send a ping to confirm a successful connection
    await client.db("admin").command({ ping: 1 });
    console.log("Pinged your deployment. You successfully connected to MongoDB!");

    // connect to a database
    const dbName = "samplesDB";
    const db = client.db(dbName);

    // add a 'samples' collection to the db (or gets the existing one)
    const collection = db.collection('samples');

    // Example 1 - Delete all docs from a collection
    // To delete all, pass an empty obj for the 'filter' param
    const deleteResult = await collection.deleteMany({})
    console.log("deleted all documents from the samples collection")
      
    // Example 2 - Insert documents into a collection
    // inserts three objects into the 'samples' collection:
    const sampleDocs = [
      { name: "sample 11" }, 
      { name: "sample 22" }, 
      { name: "sample 33" }
    ]
    const insertResult = await collection.insertMany(sampleDocs);
    console.log('\n\n\nInserted documents =>', insertResult);

    // Example 3 - Query a collection
    // Note that the 'filter' param is an empty obj (so, get all docs in the collection)
    // To get the raw data from the result, all toArray() on it
    const findResult = await collection.find({}).toArray();
    console.log('\n\n\nFound documents =>', findResult);
      
    // Example 4 - Query with filter
    // filters by finding objs that have 'name' prop value of 'sample 2'
    const filteredDocs = await collection.find({ name: 'sample 2' }).toArray();
    console.log('Found documents filtered by { name: "sample 2" } =>', filteredDocs);
        
    // Example 5 - Update a doc
    // updates obj where name='sample 2' and adds a 'someProp' prop to it
    const updateResult = await collection.updateOne({ name: 'sample 2' }, { $set: { someProp: "some value" } });
    console.log('Updated documents =>', updateResult);
    // to verify:
    const filteredDocs = await collection.find({ name: 'sample 2' }).toArray();
    console.log('Found documents filtered by { name: "sample 2" } =>', filteredDocs);
    
  } finally {
    // Ensures that the client will close when you finish/error
    await client.close();
  }
}
run().catch(console.dir);

You CAN query sub-documents in Mongo:

https://www.tutorialspoint.com/how-do-i-access-subdocuments-in-mongodb-queries