MongoDB CRUD Operations

·

7 min read

Insert and Find Documents

Insert Documents in a Collection

Insert a single document

db.grades.insertOne({
  student_id: 654321,
  class_id: 550,
})

Insert multiple documents

db.grades.insertMany([
  {
    student_id: 546789,
    class_id: 551,
  },
  {
    student_id: 777777,
    class_id: 550,
  },
  {
    student_id: 223344,
    class_id: 551,
  },
])

Find Documents in a Collection

View all the documents in the collection

db.zips.find()

Retrieve a specific document from the collection

db.zips.find({
  _id: {
    $eq: ObjectId("5c8eccc1caa187d17ca6ed16")
  }
})

Implicit syntax of $eq :

db.zips.find({
  _id: ObjectId("5c8eccc1caa187d17ca6ed16")
})

Select all documents that have a field value equal to any of the values specified in the array

db.zips.find({
  city: {
    $in: ["PHOENIX", "CHICAGO"]
  }
})

Find Documents by Using Comparison Operators

Comparison operators:

  • $gt (greater than)

  • $lt (less than)

  • $gte (greater than or equal to)

  • $lte (less than or equal to)

db.sales.find({
  "items.price": { $gt: 50 }
})
💡
Remember, to access subdocuments, we must use the syntax "field.nestedfield", which includes quotation marks.

Query on Array Elements

For instance, here we have a collection named accounts.

{
  "account_id": 470650,
  "limit": 10000,
  "products": ["CurrencyService", "Commodity", "InvestmentStock"]
}

Lets examine a query:

db.accounts.find({
  "products": "InvestmentStock"
})

The query is looking for products field that has a value equal to "InvestmentStock" or a products field with an array containing an element equal to "InvestmentStock".

If we want to query for a value or values but only return a match when they're an element of an array, we can use the $elemMatch operator.

db.account.find({
  products: {
    $elemMatch: { $eq: "InvestmentStock" }
  }
})

We can also use $elemMatch to find documents where a single array element matches multiple query criteria.

db.sales.find({
  items: {
    $elemMatch: { name: "laptop", price: { $gt: 800 }, quantity: { $gte: 1 } },
  },
})

Find Documents by Using Logical Operators

Logical Operators:

  • $and

  • $or

Find a document by using $and operator

db.routes.find({
  $and: [{ "airline.name": "Southwest Airlines" }, { stops: { $gte: 1 } }]
})

Implicit syntax of $and :

db.routes.find({
  "airline.name": "Southwest Airlines",
  stops: { $gte: 1 }
})

Find a document by using $or operator

db.routes.find({
  $or: [{ dst_airport: "SEA" }, { src_airport: "SEA" }]
})

Use the $and operator to use multiple $or expressions in our query

db.routes.find({
  $and: [
    { $or: [{ dst_airport: "SEA" }, { src_airport: "SEA" }] },
    { $or: [{ "airline.name": "American Airlines" }, { airplane: 320 }] },
  ]
})

Replace and Delete Documents

Replace a Document

To replace documents in MongoDB, we use the replaceOne() method.

db.birds.replaceOne(
  { _id: ObjectId("6286809e2f3fa87b7d86dccd") },
  {
    common_name: "Morning Dove",
    scientific_name: "Zenaida macroura",
    wingspan_cm: 37.23,
    habitat: ["urban areas", "farms", "grassland"],
    diet: ["seeds"],
  }
)

Update Documents by Using updateOne()

The $set operator replaces the value of a field with the specified value.

db.podcasts.updateOne(
  { _id: ObjectId("5e8f8f8f8f8f8f8f8f8f8f8") },
  { $set: { subscribers: 98562, }, }
)

The $push operator is used to add a new element to an array field.

db.podcasts.updateOne(
  { _id: ObjectId("5e8f8f8f8f8f8f8f8f8f8f8") },
  { $push: { hosts: "Nic Raboy" } }
)

Use the $each modifier to add multiple elements to the array

db.birds.updateOne(
  { _id: ObjectId("6268471e613e55b82d7065d7") },
  {
    $push: {
      diet: { $each: ["newts", "opossum", "skunks", "squirrels"] },
    },
  }
)

The upsert option creates a new document if no documents match the filtered criteria.

db.podcasts.updateOne(
  { title: "The Developer Hub" },
  { $set: { topics: ["databases", "MongoDB"] } },
  { upsert: true }
)

Update Documents by Using findAndModify()

The findAndModify() method is used to find and replace a single document in MongoDB.

db.podcasts.findAndModify({
  query: { _id: ObjectId("6261a92dfee1ff300dc80bf1") },
  update: { $inc: { subscribers: 1 } },
  new: true,
})
db.zips.findAndModify({
  query: { zip: 87571 },
  update: { $set: { city: "TAOS", state: "NM", pop: 40000 } },
  upsert: true,
  new: true,
})

This is a powerful method that guarantees the correct version of the document will be returned without another thread modifying the document before we are able to view it.

Update Documents by Using updateMany()

To update multiple documents, use the updateMany() method.

db.books.updateMany(
  { publishedDate: { $lt: new Date("2019-01-01") } },
  { $set: { status: "LEGACY" } }
)

It's important to note that updateMany is not an all or nothing operation. By this we mean that in the rare instance where the operation fails, updateMany will not roll back the updates. So only some documents may be updated. If this happens, we need to run updateMany again to update the remaining documents.

Delete Documents

To delete documents, use the deleteOne() or deleteMany() methods.

db.podcasts.deleteOne({ _id: Objectid("6282c9862acb966e76bbf20a") })
db.routes.deleteOne({ src_airport: "DEN", dst_airport: "XNA" })
db.podcasts.deleteMany({ category: “crime” })
db.birds.deleteMany({ sightings_count: { $lte: 10 } })

Modify Query Results

Sort and Limit Query Results

Sort Results

Use cursor.sort() to return query results in a specified order.

Within the parentheses of sort(), include an object that specifies the field(s) to sort by and the order of the sort. Use 1 for ascending order, and -1 for descending order.

// Return data on all music companies, sorted alphabetically from A to Z.
db.companies.find({ category_code: "music" }).sort({ name: 1 });

To ensure documents are returned in a consistent order, include a field that contains unique values in the sort. An easy way to do this is to include the _id field in the sort. Here's an example:

// Return data on all music companies, sorted alphabetically from A to Z. Ensure consistent sort order
db.companies.find({ category_code: "music" }).sort({ name: 1, _id: 1 });

Limit Results

Use cursor.limit() to return query results in a specified order.

Within the parentheses of limit(), specify the maximum number of documents to return.

// Return the three music companies with the highest number of employees. Ensure consistent sort order.
db.companies
  .find({ category_code: "music" })
  .sort({ number_of_employees: -1, _id: 1 })
  .limit(3);

Return Specific Data from a Query

We can limit the amount of data sent from MongoDB and improve our bandwidth performance by selecting which fields are returned. We refer to this process as projection.

To specify fields to include or exclude in the result set, add a projection document as the second parameter in the call to db.collection.find()

To include a field, set its value to 1 in the projection document.

// Return all restaurant inspections - business name, result, and _id fields only
db.inspections.find(
  { sector: "Restaurant - 818" },
  { business_name: 1, result: 1 }
)

To exclude a field, set its value to 0 in the projection document.

// Return all inspections with result of "Pass" or "Warning" - exclude date and zip code
db.inspections.find(
  { result: { $in: ["Pass", "Warning"] } },
  { date: 0, "address.zip": 0 }
)

It's important to note that inclusion and exclusion statements can't be combined in most projections. The _id field, however, is the exception.

While the _id field is included by default, it can be suppressed by setting its value to 0 in any projection.

// Return all restaurant inspections - business name and result fields only
db.inspections.find(
  { sector: "Restaurant - 818" },
  { business_name: 1, result: 1, _id: 0 }
)

Count Documents in a Collection

Use db.collection.countDocuments() to count the number of documents that match a query.

// Count number of docs in trip collection
db.trips.countDocuments({})
// Count number of trips over 120 minutes by subscribers
db.trips.countDocuments({ tripduration: { $gt: 120 }, usertype: "Subscriber" })

MongoDB CRUD Operations in Node.js

Example 1

const dbname = "bank"
const collection_name = "accounts"

const accountsCollection = client.db(dbname).collection(collection_name)

const sampleAccounts = [
 {
   account_id: "MDB011235813",
   account_holder: "Ada Lovelace",
   account_type: "checking",
   balance: 60218,
 },
 {
   account_id: "MDB829000001",
   account_holder: "Muhammad ibn Musa al-Khwarizmi",
   account_type: "savings",
   balance: 267914296,
 },
]

const main = async () => {
 try {
   await connectToDatabase()
   let result = await accountsCollection.insertMany(sampleAccounts)
   console.log(`Inserted ${result.insertedCount} documents`)
   console.log(result)
 } catch (err) {
   console.error(`Error inserting documents: ${err}`)
 } finally {
   await client.close()
 }
}

main()

Example 2

const database = client.db(dbname);
const bank = database.collection(collection_name);

const documentsToUpdate = { account_type: "checking" };

const update = { $push: { transfers_complete: "TR413308000" } }

const main = async () => {
  try {
    await connectToDatabase()
    let result = await accountsCollection.updateMany(documentsToUpdate, update)
    result.modifiedCount > 0
      ? console.log(`Updated ${result.modifiedCount} documents`)
      : console.log("No documents updated")
  } catch (err) {
    console.error(`Error updating documents: ${err}`)
  } finally {
    await client.close()
  }
}

main()