Delete the existing pets collection (by clicking the delete button in mongodb cloud) and re-insert all the data with the below command:
// reset pets:
db.pets.insertMany([
{
_id: "1",
pet_name: "juice",
breed: "maltese",
age: 11,
sex: "female",
personality: "friendly",
type: "dog"
},
{
_id: "2",
pet_name: "squack",
breed: "parakeet",
age: 4,
sex: "male",
personality: "loud",
type: "bird"
},
{
_id: "3",
pet_name: "bobby",
breed: "pigeon",
age: 2,
sex: "female",
personality: "energetic",
type: "bird"
},
{
_id: "4",
pet_name: "whalina",
breed: "blue",
age: 23,
sex: "female",
weight: 187000,
type: "whale"
},
{
_id: "5",
pet_name: "Hershey",
breed: "boxer",
age: 3,
sex: "male",
personality: "playful",
type: "dog"
},
{
_id: "6",
pet_name: "squeek",
breed: "siamese",
age: 15,
sex: "male",
weight: 2,
type: "cat"
},
{
_id: "7",
pet_name: "kipper",
breed: "greyhound",
age: 5,
sex: "male",
neutered: true,
type: "dog"
},
{
_id: "8",
pet_name: "noki",
breed: "short-haired persian",
age: 3,
sex: "female",
type: "cat"
},
{
_id: "9",
pet_name: "pooki",
age: 3,
sex: "female",
},
{
_id: "10",
pet_name: "snooki",
age: 5,
sex: "male",
},
{
_id: "11",
pet_name: "wooki",
age: 4,
sex: "male",
}
])
The below “code block” is not meant to be run inside MongoDB Atlas. Below we’re walking through the creation of our query one step at a time first.
//// find all documents where age is greater than or equal to 10.
// step 1: query for age, like normal.
age: { $gte: 10 }
// step 2: put into match:
$match: {
age: { $gte: 10 }
}
// step 3.
// In aggregations there can be multiple stages, which all need to be in a separate object.
// this is an entire stage.
{
$match: {
age: { $gte: 10 }
}
}
// step 4. aggregations are a list of stages.
[
{
$match: {
age: { $gte: 10 }
}
}
]
step 5.
// This is the final query from the steps above. We can run this.
db.pets.aggregate(
[
{
$match: {
age: { $gte: 10 }
}
}
]
)
// stage 1. find all documents where the age is greater than or equal to 10.
// stage 2. take results from stage 1, and add the # of results and store the total sum of documents in "countyodude"
db.pets.aggregate(
[
{
$match: {
age: { $gte: 10 }
}
},
{
$group: {
_id: null,
countyodude: { $sum: 1},
}
}
]
)
/// stage 1. Find all documents where age is greater than or equal to 10.
/// stage 2. take results from stage 1, store sum of results into countyodude, AND calculate the average age of results and store that value
// inside "avgdude"
db.pets.aggregate(
[
{
$match: {
age: { $gte: 10 }
}
},
{
$group: {
_id: null,
countyodude: { $sum: 1},
avgdude: { $avg: "$age" }
}
}
]
)
Aggregate with a match + sum of documents
/// Get the total number of documents in pets, and average all the ages of all the documents.
db.pets.aggregate(
[
{
$group: {
_id: null,
countyodude: { $sum: 1},
avgdude: { $avg: "$age" }
}
}
]
)
/// Remove Unnecessary fields With $unset:
db.pets.aggregate(
[
{
$match: {
age: { $gte: 10 }
}
},
{
$unset: ["age", "sex"]
}
]
)