MongoDB documents and queries
Local baseline: Node.js 22.16.0. Dependency-free application model; no external service execution. No third-party packages or external connections.
Try the local example
const books=[{_id:'b1',title:'Rivers',tags:['nature'],internalNote:'staff'}, {_id:'b2',title:'Maps',tags:['travel']}];function findBook(id){if(typeof id!=='string')return null;const b=books.find(book=>book._id===id);return b?{title:b.title,tags:[...b.tags]}:null;}console.log(JSON.stringify(findBook('b1')));console.log(findBook('b9'));Run node main.mjs in a disposable directory with the files shown. Expected standard output:
{"title":"Rivers","tags":["nature"]}nullHow it works
A book may embed a short list of tags while referencing an author shared by many books. BSON supports types beyond JSON, including ObjectId; a string is not automatically an ObjectId. Validate identifiers before conversion. The driver findOne method accepts a filter and returns a matching document or null. Use explicit approved filter fields and projections instead of accepting arbitrary query objects. The local array model illustrates nested documents and projection only. The driver snippet is partial and needs an approved MongoDB collection with string IDs.
Integration example — staged
Static candidate only. Exact package and server versions, dependency/advisory review, integration and compilation NOT RUN. Use only a reviewed disposable fixture; no real connection settings.
// Partial driver repository; books is an approved MongoDB Collection.export async function findBook(books,id){ if(typeof id!=='string'||!/^b[0-9]{1,6}$/.test(id))throw new Error('Invalid id'); return books.findOne({_id:id},{projection:{_id:0,title:1,tags:1}});}Returns the selected fields or null for a missing synthetic ID. NOT RUN.
Common mistake
Do not pass request.body directly as a MongoDB filter. Operators and field selection belong to the server-defined query contract. Document flexibility does not remove schema design.
Practice
Add a book with no tags and decide whether missing tags are valid in the application contract.
Documentation: primary source. Candidate lookup: node-mongodb-documents-and-queries-lookup. Prerequisite: node-n-plus-one-queries (platform route unverified).
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
MongoDB documents and queries — knowledge check
Apply the lesson’s contracts and identify common boundary mistakes.
Which data type is not automatically equivalent to a string?
Why build a filter from validated fields?
What does findOne return if there is no match?