insertMany() adds multiple documents to a MongoDB collection in one database operation, avoiding a separate round trip for each document. section 4.2
Use insertMany() with these practical constraints and options:
- Pass an array of documents, such as several route records, to insert them together. section 4.2
- Keep the combined documents below MongoDB’s 16 MB BSON document-size limit. section 4.2
- Use ordered processing when later inserts should stop after an earlier failure; unordered processing continues with subsequent documents and may improve performance. section 4.2
- Read acknowledged and insertedIds from the response to confirm execution and identify inserted documents. section 4.2
Bulk-inserting route documents
Run db.routes.insertMany([...]) with route documents for American Airlines, British Airways, and Air France. A successful response reports acknowledged: true and an insertedIds entry for each document. section 4.2
Listing 4.2 Inserting many documents
[primary] sample_training> db.routes.insertMany([
{
airline: { id: 413, name: 'American Airlines', alias: 'AA',
➥iata: 'AAL' },
src_airport: 'DFW',
dst_airport: 'LAX',
codeshare: '',
stops: 0,
airplane: '737'
},
{
airline: { id: 411, name: 'British Airways', alias: 'BA',
➥iata: 'BAW' },
src_airport: 'LHR',
dst_airport: 'SFO',
codeshare: 'Y',
stops: 0,
airplane: '747'
},
{
airline: { id: 412, name: 'Air France', alias: 'AF', iata: 'AFR' },
src_airport: 'CDG',
dst_airport: 'JFK',
codeshare: '',
stops: 0,
airplane: '777'
}
])
{
acknowledged: true,
insertedIds: {
'0': ObjectId('661a252acf6203ef2a1db277'),
'1': ObjectId('661a252acf6203ef2a1db278'),
'2': ObjectId('661a252acf6203ef2a1db279')
}}
[primary] sample_training>
Inspect the complete shell listing for inserting three route documents and reading their generated identifiers. section 4.2
