0
0
MongoDBquery~5 mins

Arrays in documents in MongoDB

Choose your learning style9 modes available
Introduction

Arrays let you store multiple values inside one document. This helps keep related data together in one place.

You want to store a list of items, like a shopping list or tags for a blog post.
You need to keep multiple phone numbers or emails for one person.
You want to save multiple scores or ratings for a product.
You want to group related objects, like comments on a post.
You want to keep track of multiple addresses for one user.
Syntax
MongoDB
{
  "fieldName": [value1, value2, value3, ...]
}

Arrays are written inside square brackets [].

Values inside arrays can be any type: strings, numbers, objects, or even other arrays.

Examples
This document has a field 'tags' which is an array of strings.
MongoDB
{ "tags": ["mongodb", "database", "nosql"] }
Here, 'scores' is an array of numbers.
MongoDB
{ "scores": [85, 90, 78] }
This shows an array of objects inside the 'contacts' field.
MongoDB
{ "contacts": [{ "type": "email", "value": "a@example.com" }, { "type": "phone", "value": "123-456" }] }
An empty array means no items yet, but the field is ready to hold multiple values.
MongoDB
{ "emptyArray": [] }
Sample Program

This example adds a user with a 'hobbies' array. Then it finds and prints the user document.

MongoDB
db.users.insertOne({
  name: "Alice",
  hobbies: ["reading", "hiking", "coding"]
});

// Find the user and show hobbies
const user = db.users.findOne({ name: "Alice" });
printjson(user);
OutputSuccess
Important Notes

Arrays keep related data together, making queries easier.

You can query inside arrays using special operators like $elemMatch.

Remember, arrays can hold mixed types but it's best to keep them consistent for easier use.

Summary

Arrays store multiple values inside one document field.

They can hold strings, numbers, objects, or other arrays.

Use arrays to group related data like lists or sets of items.