Getting Started and Basic Array Matching
In this first step, you will connect to the MongoDB server, create a database, and insert some sample data. Then, you will perform basic queries to find documents by matching elements within an array.
First, open the MongoDB Shell (mongosh) to interact with your database. This command will connect you to the running MongoDB instance.
mongosh
Once inside the shell, you will see a test> prompt. Let's switch to a new database named arraylab. The use command creates the database if it does not already exist and switches the current context to it.
use arraylab
Now, let's insert some documents into a new collection called products. Each document represents a product and contains two array fields: tags and colors. Copy and paste the following command into your shell:
db.products.insertMany([
{
name: "Laptop",
tags: ["electronics", "computer", "work"],
colors: ["silver", "black", "blue"]
},
{
name: "Smartphone",
tags: ["electronics", "mobile", "communication"],
colors: ["red", "blue", "green"]
},
{
name: "Headphones",
tags: ["electronics", "audio", "music"],
colors: ["black", "white"]
}
]);
To find a document that contains a specific element in an array, you can query for that value directly. This query finds all products that have the tag "mobile".
db.products.find({ tags: "mobile" });
Example Output:
[
{
_id: ObjectId("..."),
name: 'Smartphone',
tags: [ 'electronics', 'mobile', 'communication' ],
colors: [ 'red', 'blue', 'green' ]
}
]
You can also find documents where the array matches an exact sequence of elements. This query finds the product whose tags array is exactly ["electronics", "computer", "work"] in that specific order.
db.products.find({ tags: ["electronics", "computer", "work"] });
Example Output:
[
{
_id: ObjectId("..."),
name: 'Laptop',
tags: [ 'electronics', 'computer', 'work' ],
colors: [ 'silver', 'black', 'blue' ]
}
]
You can remain in the mongosh shell for the next steps. To exit the shell at any time, type exit and press Enter.