MongoDB MongoDB CRUD Operations 1 — Questions and Answers
Question 1: Which method is used to insert a single document into a MongoDB collection?
- insertOne() (Correct answer)
- insertMany()
- save()
- addDocument()
Correct answer: insertOne()
insertOne() inserts a single document into a collection and returns an acknowledgment with the inserted document's _id.
Question 2: What does the findOne() method return when no matching document is found?
- An empty object {}
- null (Correct answer)
- undefined
- An empty array []
Correct answer: null
findOne() returns null when no document matches the specified query filter.
Question 3: Which update operator sets the value of a field in a document?
- $push
- $inc
- $set (Correct answer)
- $unset
Correct answer: $set
$set assigns a new value to the specified field, creating it if it does not already exist.
Question 4: What option must be passed to updateOne() to create a new document if no match is found?
- { createNew: true }
- { insert: true }
- { upsert: true } (Correct answer)
- { merge: true }
Correct answer: { upsert: true }
Setting upsert: true causes MongoDB to insert a new document when no document matches the filter criteria.
Question 5: Which method removes a single document that matches the filter from a collection?
- removeOne()
- deleteFirst()
- deleteOne() (Correct answer)
- dropOne()
Correct answer: deleteOne()
deleteOne() deletes the first document that matches the filter, returning the count of deleted documents.
Question 6: What does the $inc operator do in an update operation?
- Inserts a new field
- Increments or decrements a numeric field by a specified amount (Correct answer)
- Indexes a field
- Includes a field in projection
Correct answer: Increments or decrements a numeric field by a specified amount
$inc adds the specified value to a field's current value, and a negative value effectively decrements it.
Which method is used to insert a single document into a MongoDB collection?