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').insertOne({
name: 'Mobile'
})
db.getCollection('category').insertOne({
name: 'Laptop'
})
db.getCollection('category').insertOne({
name: 'Tivi'
})
/* Create Product collection */
db.createCollection('product');
/* Dumping data for `product` collection */
db.getCollection('product').insertOne({
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').insertOne({
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').insertOne({
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').insertOne({
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').insertOne({
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').insertOne({
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').insertOne({
name: 'Tivi 2',
price: 86,
quantity: 23,
status: false,
date: ISODate('2017-09-24'),
categoryId: ObjectId('5a30de130867edfa4571166a'),
brand: {
_id: new ObjectId(),
name: 'brand 3'
}
});
Use Less Than Operator in Query Commands
db.getCollection('product').find({ price: { $lt: 14 } })
Output
/* 1 */
{
"_id" : ObjectId("5a30ec580867edfa4571166e"),
"name" : "Mobile 2",
"price" : 12.0,
"quantity" : 7.0,
"status" : true,
"date" : ISODate("2017-11-14T00:00:00.000Z"),
"categoryId" : ObjectId("5a30de130867edfa45711668"),
"brand" : {
"_id" : ObjectId("5a30ec580867edfa4571166d"),
"name" : "brand 2"
}
}