Create Database
Create a database with the name is learnmongodb. This database have 2 collections: Category collection and Product collection. Category collection and Product collection have a One to Many. One category can have many products and One product belongs to one and only one category.
/* Create learnmongodb database */
use learnmongodb
/* Create Category collection */
db.createCollection('category');
/* Dumping data for `category` collection */
db.getCollection('category').insert({
name: 'Mobile'
})
db.getCollection('category').insert({
name: 'Laptop'
})
db.getCollection('category').insert({
name: 'Tivi'
})
/* Create Product collection */
db.createCollection('product');
/* Dumping data for `product` collection */
db.getCollection('product').insert({
name: 'Mobile 1',
price: 45,
quantity: 4,
status: true,
date: ISODate('2016-10-20'),
categoryId: ObjectId('5a30de130867edfa45711668'),
brand: {
_id: new ObjectId(),
name: 'brand 1'
}
});
db.getCollection('product').insert({
name: 'Mobile 2',
price: 12,
quantity: 7,
status: true,
date: ISODate('2017-11-14'),
categoryId: ObjectId('5a30de130867edfa45711668'),
brand: {
_id: new ObjectId(),
name: 'brand 2'
}
});
db.getCollection('product').insert({
name: 'Mobile 3',
price: 28,
quantity: 8,
status: true,
date: ISODate('2017-11-20'),
categoryId: ObjectId('5a30de130867edfa45711668'),
brand: {
_id: new ObjectId(),
name: 'brand 3'
}
});
db.getCollection('product').insert({
name: 'Laptop 1',
price: 39,
quantity: 12,
status: false,
date: ISODate('2017-12-26'),
categoryId: ObjectId('5a30de130867edfa45711669'),
brand: {
_id: new ObjectId(),
name: 'brand 1'
}
});
db.getCollection('product').insert({
name: 'Laptop 2',
price: 86,
quantity: 23,
status: true,
date: ISODate('2017-03-11'),
categoryId: ObjectId('5a30de130867edfa45711669'),
brand: {
_id: new ObjectId(),
name: 'brand 1'
}
});
db.getCollection('product').insert({
name: 'Tivi 1',
price: 22,
quantity: 7,
status: true,
date: ISODate('2017-06-26'),
categoryId: ObjectId('5a30de130867edfa4571166a'),
brand: {
_id: new ObjectId(),
name: 'brand 1'
}
});
db.getCollection('product').insert({
name: 'Tivi 2',
price: 86,
quantity: 23,
status: false,
date: ISODate('2017-09-24'),
categoryId: ObjectId('5a30de130867edfa4571166a'),
brand: {
_id: new ObjectId(),
name: 'brand 3'
}
});
The Biggest Price
db.getCollection('product').aggregate( [ { $group: { _id: '', total: { $max: "$price" } } } ] )
Output
/* 1 */
{
"_id" : "",
"total" : 86.0
}
The Smallest Price
db.getCollection('product').aggregate( [ { $group: { _id: '', total: { $min: "$price" } } } ] )
Output
/* 1 */
{
"_id" : "",
"total" : 12.0
}