Explorer
MongoDB

Insert a new book `{ _id: 5, title: "New Book", pages: 250 }` into the `books` collection and return the insert result.

Problem Statement

<p>Insert a new book <code>{ <code>_id</code>: 5, <code>title</code>: "New Book", pages: 250 }</code> into the <code>books</code> collection and return the insert result.</p>

Examples

Input: books collection: +-----+----------+-------+ | _id | title | pages | +-----+----------+-------+ | 1 | Old Book | 100 | +-----+----------+-------+

Output: +------------+--------------+ | insertedId | acknowledged | +------------+--------------+ | 5 | true | +------------+--------------+

Explanation: Documents containing the matching array elements are selected from the collection.

Complexity

Time Complexity: -

Space Complexity: -

Hints

šŸ’” Hint 1: Use db.<collection>.find(<filter>) to query the documents in the collection. šŸ’” Hint 2: Pass an empty object {} to retrieve all documents, or specify key-value pairs for exact matching. šŸ’” Hint 3: Chain .toArray() to resolve the MongoDB cursor into a JavaScript array: return db.<collection>.find(...).toArray();

Editorial & Approach

Problem Overview & Intuition

To solve "Insert One Document (insertOne)", we query the MongoDB document store. The goal is to insert a new book `{ _id: 5, title: "new book", pages: 250 }` into the `books` collection and return the insert result. Using a targeted find query, the database engine filters and structures the BSON documents efficiently.

Step-by-Step Approach

  1. Identify Target Collection: Access the collection through the db instance.
  2. Construct Query / Pipeline: Build the query filter with appropriate comparison operators.
  3. Resolve Cursor: Invoke .toArray() to transform the query cursor into the required array of documents.

Optimal Implementation (MongoDB)

function solve(db) {
  return db.books.insertOne({ _id: 5, title: "New Book", pages: 250 });
}

Complexity Analysis

Time Complexity O(N) collection scan (O(log N) if index is present on filtered fields).
Space Complexity O(K) where K is the number of returned documents in memory.

Key Considerations & Edge Cases

  • Empty Collections: If no documents match, the query cleanly returns an empty array [].
  • Missing / NULL Fields: Missing fields in documents are handled safely without throwing runtime exceptions.
  • Type Coercion: BSON types (ObjectId, Numbers, Strings) are compared strictly according to MongoDB specifications.

Insert One Document (insertOne)

Easy

Insert a new book { _id: 5, title: "New Book", pages: 250 } into the books collection and return the insert result.

Example Scenarios
1Example 1
Input:
books collection
_idtitlepages
1Old Book100
Output:
insertedIdacknowledged
5true
Explanation:

Documents containing the matching array elements are selected from the collection.

MongoDB Editor
Loading Editor...
Query Results (JSON)

Run your MongoDB code to see results here.