Data Manipulation


Data Manipulation Interview with follow-up questions

1. What are the basic commands for data manipulation in MongoDB?

The basic data-manipulation (CRUD) commands in MongoDB, using the modern mongosh methods:

  • Create: insertOne() adds a single document; insertMany() adds an array of documents.
  • Read: find() returns a cursor over all matching documents; findOne() returns the first match.
  • Update: updateOne() / updateMany() modify matching documents using operators like $set, $inc, $push; replaceOne() swaps a whole document.
  • Delete: deleteOne() / deleteMany() remove matching documents.

For example:

db.users.insertOne({ name: "Ada", age: 36 })
db.users.find({ age: { $gt: 30 } })
db.users.updateOne({ name: "Ada" }, { $set: { active: true } })
db.users.deleteOne({ name: "Ada" })

An important 2026 gotcha: the legacy helpers insert(), update(), and remove() are deprecated/removed — interviewers expect the explicit *One/*Many methods, which make the "one vs. many" intent clear and return useful result metadata (e.g. matchedCount, modifiedCount). For high-volume mixed operations, mention bulkWrite(). Also note we use mongosh; the old mongo shell was removed in MongoDB 6.0.

↑ Back to top

Follow-up 1

What is the difference between remove and delete in MongoDB?

In MongoDB, remove and delete are two commands used to remove documents from a collection, but they have slight differences:

  • remove is used to remove one or more documents from a collection based on the specified criteria. It can remove multiple documents if the criteria match.
  • delete is used to remove a single document from a collection based on its _id field. It can only remove one document at a time.

Follow-up 2

How can you find a specific document in MongoDB?

To find a specific document in MongoDB, you can use the find command with a query parameter. The syntax is as follows:

db.collection.find(query)
  • db.collection refers to the collection where the document will be searched.
  • find is the command to find documents.
  • query is the criteria to select the document(s) to be returned. It can include conditions on specific fields or use operators like $eq, $gt, $lt, etc.

Follow-up 3

Can you explain the syntax of the insert command?

The syntax of the insert command in MongoDB is as follows:

db.collection.insert(document)
  • db.collection refers to the collection where the document will be inserted.
  • insert is the command to insert a document.
  • document is the JSON object representing the document to be inserted.

Follow-up 4

How does the update command work in MongoDB?

The update command in MongoDB is used to modify an existing document in a collection. It has the following syntax:

db.collection.update(query, update, options)
  • db.collection refers to the collection where the document will be updated.
  • update is the modification to be applied to the document.
  • query is the criteria to select the document(s) to be updated.
  • options is an optional parameter that can be used to specify additional options, such as whether to update multiple documents or to upsert (insert if not found).

2. How can you insert multiple documents at once in MongoDB?

To insert multiple documents at once, use insertMany(), which takes an array of documents and inserts them into the collection in mongosh:

const documents = [
  { name: "John", age: 25 },
  { name: "Jane", age: 30 },
  { name: "Bob", age: 35 }
];

db.users.insertMany(documents);

Each document gets an auto-generated _id if you don't supply one, and the result returns the insertedIds.

Two follow-ups interviewers like to probe:

  • Ordered vs. unordered: by default insertMany is ordered — it stops at the first error and leaves the rest uninserted. Pass { ordered: false } to keep going past failures (e.g. duplicate-key errors), inserting all the valid documents and reporting the failures at the end:
db.users.insertMany(documents, { ordered: false });
  • Bulk/mixed writes: for large volumes or mixed insert/update/delete operations, use bulkWrite(), which batches them efficiently in one round trip.

Note we use mongosh and the modern insertMany method — the legacy insert() helper has been removed.

↑ Back to top

Follow-up 1

What happens if one of the insert operations fails?

If one of the insert operations fails during a bulk insert in MongoDB, the entire operation will be rolled back. This means that none of the documents will be inserted into the collection. MongoDB ensures atomicity for bulk inserts, so either all the documents are inserted successfully or none of them are.

Follow-up 2

How does MongoDB handle duplicate entries during a bulk insert?

During a bulk insert in MongoDB, if there are duplicate entries for a unique index, the operation will fail and none of the documents will be inserted. MongoDB enforces unique indexes and prevents duplicate entries from being inserted. If you want to handle duplicates manually, you can use the ordered option when calling insertMany() and set it to false. This will allow the operation to continue even if there are duplicate entries, but only the non-duplicate documents will be inserted.

Follow-up 3

Can you provide an example of a bulk insert command?

Sure! Here is an example of a bulk insert command using the insertMany() method in MongoDB:

const documents = [
  { name: 'John', age: 25 },
  { name: 'Jane', age: 30 },
  { name: 'Bob', age: 35 }
];

db.collection('users').insertMany(documents);

3. What is the role of the _id field in MongoDB?

The _id field is the primary key that uniquely identifies a document within its collection. If you don't provide one on insert, MongoDB generates a 12-byte ObjectId (4-byte timestamp + 5-byte random + 3-byte counter). It's backed by a unique index that exists automatically on every collection, so lookups by _id are fast, and it is immutable — you can't change it after insert.

You can supply your own _id instead of letting MongoDB generate one — a string, number, UUID, or even a sub-document — which is handy when you have a natural unique key (an email, SKU, order number) and want to avoid a second unique index.

A couple of follow-ups interviewers often add:

  • Because an ObjectId embeds a creation timestamp, sorting by _id roughly sorts by insertion time, and you can extract that time (e.g. objectId.getTimestamp()).
  • That same monotonic property means sequential inserts cluster on one side of the index, which can create a write hotspot at high throughput or with _id-based sharding — so for write-heavy/sharded workloads you'd consider a hashed shard key rather than a raw ObjectId.

This question (and the _id role question earlier) is a favorite because the naive "it's just an auto ID" answer misses the immutability, the automatic unique index, and the hotspot trade-off.

↑ Back to top

Follow-up 1

Is the _id field always required?

No, the _id field is not always required. If you do not provide a value for the _id field when inserting a document, MongoDB will automatically generate a unique identifier for the document. However, if you do provide a value for the _id field, it must be unique within the collection. If a document with the same _id value already exists, MongoDB will throw a duplicate key error.

Follow-up 2

Can you customize the _id field?

Yes, you can customize the _id field in MongoDB. By default, the _id field is of type ObjectId, which is a 12-byte identifier that consists of a timestamp, a machine identifier, a process identifier, and a random value. However, you can also use other data types for the _id field, such as strings or integers. When customizing the _id field, it is important to ensure that the values are unique within the collection to avoid duplicate key errors.

Follow-up 3

What is the default type of the _id field?

The default type of the _id field in MongoDB is ObjectId. ObjectId is a BSON data type that is designed to be globally unique and sortable. It provides a good balance between uniqueness, size, and performance. However, as mentioned earlier, you can also use other data types for the _id field if needed.

4. How can you update a specific field in a document in MongoDB?

To update a specific field, use updateOne() (or updateMany() for all matches) with the $set operator, which changes only the named field and leaves the rest of the document intact:

db.users.updateOne(
  { name: "John" },
  { $set: { age: 26 } }
)

updateOne modifies the first document matching the filter; updateMany modifies all of them. The result includes matchedCount and modifiedCount so you can confirm the effect.

Follow-ups worth knowing:

  • Other field operators: $inc (increment), $unset (remove a field), $rename, $push/$pull (arrays), and $mul. Without $set/an operator, you'd replace the whole document — that's replaceOne, a common gotcha.
  • Upsert: add { upsert: true } to insert a new document when nothing matches the filter.
  • Atomic read-and-modify: use findOneAndUpdate() when you need the document returned (before or after) in the same atomic operation.
db.users.updateOne(
  { name: "John" },
  { $set: { age: 26 } },
  { upsert: true }
)

Note these are the modern mongosh methods — the legacy update() helper has been removed, so always reach for updateOne/updateMany.

↑ Back to top

Follow-up 1

What happens if the document to be updated does not exist?

If the document to be updated does not exist, the updateOne() or updateMany() method will not make any changes to the collection. It will not throw an error or create a new document.

Follow-up 2

Can you update multiple documents at once?

Yes, you can update multiple documents at once using the updateMany() method. Here is an example:

db.collection.updateMany(
   {  },
   { $set: { :  } }
)

This will update all documents that match the filter with the new value for the specified field.

Follow-up 3

What is the difference between $set and $inc update operators?

The $set and $inc are both update operators in MongoDB, but they have different purposes:

  • $set is used to set the value of a field in a document. It can be used to update an existing field or add a new field to the document.

  • $inc is used to increment or decrement the value of a numeric field in a document. It can only be used with numeric fields and requires a numeric value to be specified.

Here are examples of using both operators:

// Using $set
db.collection.updateOne(
   {  },
   { $set: { :  } }
)

// Using $inc
db.collection.updateOne(
   {  },
   { $inc: { :  } }
)

5. How can you delete a document in MongoDB?

To delete documents, use deleteOne() or deleteMany(). deleteOne() removes the first document matching the filter; deleteMany() removes all matching documents.

Here's deleteOne() in mongosh:

db.users.deleteOne({ name: "John" })

This deletes the first document where name is "John". To remove every matching document:

db.users.deleteMany({ status: "inactive" })

The result returns a deletedCount so you can confirm how many were removed.

Follow-ups interviewers commonly add:

  • Delete everything in a collection: db.users.deleteMany({}) removes all documents but keeps the collection and its indexes; db.users.drop() removes the collection entirely (faster, but drops indexes too).
  • Atomic delete-and-return: findOneAndDelete() deletes a document and returns it in one atomic step.
  • Empty filter caution: deleteMany({}) with no filter wipes the whole collection — a classic foot-gun to call out.

Note these are the modern mongosh methods; the legacy remove() helper has been removed, so use deleteOne/deleteMany.

↑ Back to top

Follow-up 1

Can you delete multiple documents at once?

Yes, you can delete multiple documents at once in MongoDB using the deleteMany() method. This method deletes all documents that match the specified filter.

Here's an example of deleting multiple documents using deleteMany():

# Assuming you have a collection named 'my_collection'

my_collection.deleteMany({ 'age': { '$gte': 30 } })

This will delete all documents in the collection where the 'age' field is greater than or equal to 30.

Follow-up 2

What happens if the document to be deleted does not exist?

If the document to be deleted does not exist, the deleteOne() method will not throw an error. It will simply return a result object with a deletedCount property set to 0, indicating that no document was deleted.

Here's an example:

# Assuming you have a collection named 'my_collection'

result = my_collection.deleteOne({ 'name': 'Jane' })
print(result.deletedCount)  # Output: 0

In this example, the document with the 'name' field equal to 'Jane' does not exist, so the deletedCount property is 0.

Follow-up 3

How can you delete all documents in a collection?

To delete all documents in a collection, you can use the deleteMany() method without specifying a filter. This will delete all documents in the collection.

Here's an example:

# Assuming you have a collection named 'my_collection'

my_collection.deleteMany({})

This will delete all documents in the collection.

Live mock interview

Mock interview: Data Manipulation

Intermediate ~5 min Your own free AI key

Your voice and your AI key never touch our servers; the key stays in this browser and is sent only to Google. Only your round scores are saved to track progress.