insertOne() inserts one document into a MongoDB collection. MongoDB creates the database and collection when the first document is saved, if they do not already exist. section 2.6.2 section 4.2
Use insertOne() in mongosh as follows:
- Select a database with use booksData. section 2.6.2
- Call db.books.insertOne() with one document, such as { title: "MongoDB 8.0 in Action" }. section 2.6.2
- Read the response: acknowledged: true confirms execution, while insertedId identifies the new document. section 4.2
- Provide your own _id when the application needs a custom identifier; otherwise MongoDB supplies an ObjectId. section 4.2
Insert a route
db.routes.insertOne({ airline: { id: 410, name: 'Lufthansa', alias: 'LH', iata: 'DLH' }, src_airport: 'MUC', dst_airport: 'JFK', codeshare: '', stops: 0, airplane: 'A380' }) returns acknowledged: true and an insertedId. section 4.2
Choose insertMany() instead for multiple documents; it performs a bulk operation rather than a database round trip for each document. Schema validation can reject an insertOne() request when fields violate defined rules, returning details about the failures. section 4.2 section 5.4.2
use booksDatadb.books.insertOne({"title":"MongoDB 8.0 in Action"})
Open the compact mongosh example showing database selection followed by a single-document insertion. section 2.6.2
db.routes.insertOne({
flight_id: "XYZ123", // flight_id should start with "FL"
airline: {
id: -410, // airline.id must be a positive integer
name: "Delta Airlines",
alias: "2B",
iata: "ARD"
},
src_airport: {
code: "JFK",
name: "JFK International Airport"
},
dst_airport: {
code: "999", // dst_airport.code must be a valid code
name: "Unknown Airport"
},
airplane: "CR2",
stops: 0
})
Inspect an invalid route insertion and the validation constraints it violates. section 5.4.2
