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 get only values in arrays with MongoDB aggregate?
To get only values from arrays in MongoDB aggregate operations, use the $map operator within $project to transform array elements and extract specific field values into a new array structure.
Syntax
db.collection.aggregate([
{
$project: {
arrayField: {
$map: {
input: "$arrayField",
as: "item",
in: ["$$item.field1", "$$item.field2"]
}
}
}
}
]);
Sample Data
db.demo411.insertOne({
"Information": [
{
"Name1": "Chris",
"Name2": "David"
},
{
"Name1": "John",
"Name2": "John"
}
]
});
{
"acknowledged": true,
"insertedId": ObjectId("5e70f19715dc524f70227682")
}
Display Current Document
db.demo411.find();
{
"_id": ObjectId("5e70f19715dc524f70227682"),
"Information": [
{ "Name1": "Chris", "Name2": "David" },
{ "Name1": "John", "Name2": "John" }
]
}
Example: Extract Array Values
Extract only the Name1 and Name2 values from the Information array ?
db.demo411.aggregate([
{
$project: {
_id: 0,
Information: {
$map: {
input: "$Information",
as: "out",
in: ["$$out.Name1", "$$out.Name2"]
}
}
}
}
]);
{ "Information": [ [ "Chris", "David" ], [ "John", "John" ] ] }
How It Works
-
$mapiterates through each element in the Information array -
inputspecifies the source array field -
ascreates a variable name for each array element -
indefines the transformation - creates a new array with extracted values
Conclusion
Use $map with $project to extract specific field values from array elements. This transforms complex nested objects into simplified arrays containing only the values you need.
Advertisements
