From mongosh to the Driver: find, insertOne and toArray

Every mongosh query has a twin in the Node.js driver, written with db.collection("pets"), await, a projection inside an options object, toArray() to read a cursor, and new ObjectId(id) imported from the driver, and insertOne gives back the new document's insertedId.

Journeyman · MongoDB · Node.js · Updated

By

After this lesson you can

  • Turn a mongosh find, findOne or countDocuments into its driver twin with db.collection, await, projection and toArray
  • Find a document by an id from a web address with new ObjectId(id), and read what insertOne gives back

Key takeaways

  • In Node, db.collection("pets") is the collection mongosh calls db.pets, and every call that asks MongoDB something is awaited.
  • find gives back a cursor, and toArray() reads every document it found into an ordinary array.
  • The driver's find takes the fields to show inside an options object, as projection, and quietly ignores them when they're passed the mongosh way.
  • An id from a web address is text, so it needs new ObjectId(id), with ObjectId imported from the mongodb package, before it can match an _id.
  • insertOne gives back acknowledged and insertedId, the new document's _id, which toString() turns into text.

You've written dozens of queries in mongosh. An app runs those same queries, from its own code, with the driver. Moving a query from the shell, where you tried it, into a route is something you'll do again and again, and it changes a handful of small things in how the query is written. This lesson lists them, one at a time.

The examples use the center's 12 pets in the maple_street database, from Connecting from Node: MongoClient and the Connection String, and a .env file that holds MONGODB_URI.

The same question, asked twice

The center's cat page wants every cat's name and age. In mongosh you'd write:

db.pets.find({ species: "cat" }, { _id: 0, name: 1, age: 1 })
[
  { name: 'Mochi', age: 2 },
  { name: 'Juniper', age: 5 },
  { name: 'Olive', age: 9 },
  { name: 'Pickles', age: 1 },
  { name: 'Ziggy', age: 4 }
]

Here is its twin from Node, in a file named find-cats.js:

import { MongoClient } from "mongodb";

const client = new MongoClient(process.env.MONGODB_URI);
await client.connect();
const db = client.db("maple_street");

const cats = await db.collection("pets")
  .find({ species: "cat" }, { projection: { _id: 0, name: 1, age: 1 } })
  .toArray();
console.log(cats);

await client.close();
node --env-file=.env find-cats.js
[
  { name: 'Mochi', age: 2 },
  { name: 'Juniper', age: 5 },
  { name: 'Olive', age: 9 },
  { name: 'Pickles', age: 1 },
  { name: 'Ziggy', age: 4 }
]

The same five cats, and three changes. db.pets becomes db.collection("pets"): in mongosh, db. followed by any name is a collection, while in Node, db is an ordinary object and you ask it for a collection by name. The filter is untouched. And the call ends with toArray() and starts with await.

A cursor, and toArray()

A deli counter doesn't hand you every order at once: you take a ticket, and the orders come out as they're ready. find works the same way. It gives back a cursor, a ticket for the answer that hands the documents over a batch at a time. mongosh reads the cursor for you and prints the first 20 (type it for more). Node never reads it on its own: toArray() reads every document into an ordinary array, and because the documents come from another program, it gives back a promise, so it needs await. Leave the await out, and console.log shows the pager from Waiting for the Database: async, await and try/catch instead of the cats:

Promise { <pending> }

Where the fields to show go

The second argument is where the twins differ quietly. mongosh's find takes the fields to show second. The driver's find takes an options object second, and the fields go inside it, under projection. Pass them the mongosh way, and the driver doesn't complain; it ignores them:

const cats = await db.collection("pets").find({ species: "cat" }, { _id: 0, name: 1, age: 1 }).toArray();
console.log(cats[0]);
{
  _id: new ObjectId('6740c0000000000000000002'),
  name: 'Mochi',
  species: 'cat',
  age: 2,
  traits: [ 'calm', 'indoor only' ],
  status: 'available'
}

Every field came back. When a projection seems to do nothing in Node, look for the missing projection:. Sorting, skipping and limiting chain on the cursor exactly as in mongosh, before toArray(): .find({ species: "dog" }).sort({ age: -1 }).limit(3).toArray().

Ids: new ObjectId(id)

A pet's page has an address like /pets/6740c0000000000000000002, and Express hands you the end of it as text. The _id in the database is an ObjectId, and text never equals an ObjectId, however alike they look:

import { MongoClient, ObjectId } from "mongodb";

const client = new MongoClient(process.env.MONGODB_URI);
await client.connect();
const pets = client.db("maple_street").collection("pets");

console.log(await pets.findOne({ _id: "6740c0000000000000000002" }));
console.log(await pets.findOne({ _id: new ObjectId("6740c0000000000000000002") }));

await client.close();
null
{
  _id: new ObjectId('6740c0000000000000000002'),
  name: 'Mochi',
  species: 'cat',
  age: 2,
  traits: [ 'calm', 'indoor only' ],
  status: 'available'
}

The first findOne finds nothing and gives back null, as in mongosh. The second turns the text into an ObjectId first. mongosh writes ObjectId("..."); in Node you import ObjectId from the mongodb package and write new ObjectId("..."), where new makes a new object of that kind. Node also prints an ObjectId as new ObjectId('...').

Adding a pet: insertOne

Adding a pet is the same call as in mongosh, awaited. With pets from the code above:

const result = await pets.insertOne({
  name: "Waffles",
  species: "dog",
  age: 4,
  traits: ["good with kids"],
  status: "available",
});
console.log(result);
console.log(await pets.countDocuments({ species: "dog" }));
{
  acknowledged: true,
  insertedId: new ObjectId('6afca1c5ab3ed6b5a010f440')
}
6

acknowledged: true means the server saved it, and insertedId is the new _id (yours will be different). An API sends ids as text, and result.insertedId.toString() gives "6afca1c5ab3ed6b5a010f440". The count is the five dogs plus Waffles.

Here are all the changes in one place:

In mongosh With the driver
db.pets db.collection("pets")
find(filter, { name: 1 }) find(filter, { projection: { name: 1 } })
Results printed for you await the call, and toArray() on a cursor
ObjectId("...") new ObjectId("..."), imported from "mongodb"
findOne, insertOne, countDocuments, updateOne, sort, limit The same names and the same filters

Check yourself

2 questions to try on the lesson page.

So what

The query you test in mongosh is the query your app runs: a few small changes in how it's written, and the filter moves into your app unchanged.

Key terms

Related