How to Insert Array in MongoDB: Syntax and Examples
To insert an array in MongoDB, include the array as a value in the document object passed to
insertOne() or insertMany(). MongoDB stores arrays natively, so you just assign the array to a field like { items: [1, 2, 3] }.Syntax
Use the insertOne() method on a collection to add a document. The document can have fields with array values. Arrays are enclosed in square brackets [] and can contain any data type.
db.collection.insertOne(document): Inserts one document.document: An object with fields and values, where values can be arrays.
javascript
db.collection.insertOne({ fieldName: [value1, value2, value3] })Example
This example inserts a document with an array field tags containing three strings. It shows how MongoDB stores arrays directly inside documents.
javascript
db.products.insertOne({ name: "Notebook", tags: ["stationery", "paper", "office"] })Output
{ acknowledged: true, insertedId: ObjectId("someObjectId") }
Common Pitfalls
Common mistakes include:
- Using parentheses
()instead of square brackets[]for arrays. - Trying to insert arrays as strings instead of actual arrays.
- Not using valid JSON-like syntax for documents.
Always ensure arrays are properly formatted and passed as arrays, not strings.
javascript
/* Wrong: array as string */ db.collection.insertOne({ items: "[1, 2, 3]" }) /* Right: array as array */ db.collection.insertOne({ items: [1, 2, 3] })
Quick Reference
Remember these tips when inserting arrays in MongoDB:
- Use square brackets
[]for arrays. - Arrays can contain mixed data types.
- Insert arrays as part of the document object.
- Use
insertOne()orinsertMany()to add documents.
Key Takeaways
Insert arrays by including them as field values in the document object.
Use square brackets [] to define arrays in MongoDB documents.
Avoid passing arrays as strings; always use actual array syntax.
Use insertOne() or insertMany() methods to insert documents with arrays.
MongoDB stores arrays natively and supports mixed data types inside arrays.