MongoDB Utility Methods: Find by ObjectId, validate() & Storage Size
Learn how to query MongoDB by _id/ObjectId, validate a collection for corruption, and check a collection's storage size with storageSize() and totalSize().
Handy MongoDB Utility Methods
Find by _id / ObjectId
The _id field is stored as a special ObjectId type, not a plain string — you must wrap the value in ObjectId(...) for the query to match.
db.employees.find({ _id: "64ba88c4768ace4777482ea1" })
// returns nothing — _id is not a plain string
db.employees.find({ _id: ObjectId("64ba88c4768ace4777482ea1") })
// this is the correct way to query by _id
validate()
Scans a collection's data and indexes for corruption and returns a detailed report.
db.employees.validate()
// {
// ns: 'rahultechnology.employees',
// nInvalidDocuments: 0,
// nrecords: 9,
// valid: true,
// ...
// }
db.employees.validate({ full: true }) // deeper, more thorough scan
db.employees.validate({ repair: true }) // attempt to repair issues found
Checking Collection Storage
Three quick methods tell you how much disk space a collection is using:
db.employees.storageSize()
// total bytes allocated for storing documents
db.employees.totalSize()
// document data size + all index sizes combined
db.employees.totalIndexSize()
// total size of all indexes on the collection
Advertisement728 x 90
Common Errors & Troubleshooting
find({ _id: "some-hex-string" })returning nothing — this is the single most common MongoDB beginner mistake —_idis anObjectId, not a string; wrap it:find({ _id: ObjectId("some-hex-string") }).ObjectIdthrowing an error on an invalid string —ObjectId()requires exactly a 24-character hex string; passing anything else (like a UUID, or a string that's the wrong length) throws immediately.validate()reportingvalid: false— this indicates real corruption; back up the collection immediately and consider{ repair: true }, or restoring from a recent backup if repair doesn't resolve it.
Key Takeaways
- Always wrap
_idlookups inObjectId(...)— a plain string will never match. validate()is your go-to health check when a collection behaves unexpectedly.storageSize(),totalSize(), andtotalIndexSize()help you keep an eye on disk usage per collection.
Advertisement320 x 100