Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to store array values in MongoDB?
MongoDB supports array data types natively, allowing you to store multiple values within a single document field. Arrays can contain simple values, objects, or even nested arrays.
Syntax
db.collection.insertOne({
"fieldName": [value1, value2, value3]
});
// For arrays of objects
db.collection.insertOne({
"fieldName": [
{"key1": "value1"},
{"key2": "value2"}
]
});
Sample Data
Let us create a collection with documents containing array values ?
db.demo321.insertMany([
{
"UserDetails": [
{"UserId": 101, "UserName": "Chris"},
{"UserId": 102, "UserName": "Mike"}
]
},
{
"UserDetails": [
{"UserId": 103, "UserName": "Bob"},
{"UserId": 104, "UserName": "Sam"}
]
}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e511248f8647eb59e56206a"),
ObjectId("5e511259f8647eb59e56206b")
]
}
Example: Query Array Data
Display all documents from the collection ?
db.demo321.find().pretty();
{
"_id": ObjectId("5e511248f8647eb59e56206a"),
"UserDetails": [
{ "UserId": 101, "UserName": "Chris" },
{ "UserId": 102, "UserName": "Mike" }
]
}
{
"_id": ObjectId("5e511259f8647eb59e56206b"),
"UserDetails": [
{ "UserId": 103, "UserName": "Bob" },
{ "UserId": 104, "UserName": "Sam" }
]
}
Key Points
- Arrays in MongoDB can store mixed data types (strings, numbers, objects, nested arrays).
- Use
insertMany()for bulk insertion of multiple documents with arrays. - Array elements maintain their insertion order by default.
Conclusion
MongoDB natively supports array storage within documents, making it ideal for storing related data collections. Arrays can contain simple values or complex objects, providing flexibility for various data structures.
Advertisements
