MongoDb Programs
MongoDb Programs
Sl PROGRAMS
No
1 a. Illustration of Where Clause, AND,OR operations in MongoDB.
db.createcollection(“studentdetails”)
Output:
{
acknowledged: true,
insertedIds: {
'0': ObjectId('6699fec7bb5b4fc21146b799'),
'1': ObjectId('6699fec7bb5b4fc21146b79a'),
'2': ObjectId('6699fec7bb5b4fc21146b79b')
}
}
Output:
{
acknowledged: true,
insertedId: null,
matchedCount: 0,
modifiedCount: 0,
upsertedCount: 0
}
Delete One Document
db.student.deleteOne({Anna:101})
Output:
{ acknowledged: true, deletedCount: 0 }
posts> db.posts.find({}, {title: 1, date: 1})
IV SEM MONGO DB LAB MANUAL DEPT Of AIML
Output:
[
{
_id: ObjectId('6699fec7bb5b4fc21146b799'),
title: 'Post Title 2',
date: 'Fri Jul 19 2024 11:21:03 GMT+0530 (India Standard Time)'
},
{
_id: ObjectId('6699fec7bb5b4fc21146b79a'),
title: 'Post Title 3',
date: 'Fri Jul 19 2024 11:21:03 GMT+0530 (India Standard Time)'
},
{
_id: ObjectId('6699fec7bb5b4fc21146b79b'),
title: 'Post Title 4',
date: 'Fri Jul 19 2024 11:21:03 GMT+0530 (India Standard Time)'
}]
Projection:
db.posts.find({}, {title: 1, date: 1})
IV SEM MONGO DB LAB MANUAL DEPT Of AIML
2 a. Develop a MongoDB query to select certain fields and ignore some fields of the
documents from any collection.
db.collection.insertMany([{name:"abc",age:25,gender:"female"},{name:"ghj",age
:55,gender:"male"},{name:"cvb",age:52,gender:"female"},{name:"yhn",age:80,g
ender:"female"},{name:"wsg",age:18,gender:"male"},{name:"jhc",age:29,gender:
"male"},{name:"jhc",age:29,gender:"male"}])
Output:
{
acknowledged: true,
insertedIds: {
'0': ObjectId('669a0268bb5b4fc21146b7a0'),
'1': ObjectId('669a0268bb5b4fc21146b7a1'),
'2': ObjectId('669a0268bb5b4fc21146b7a2'),
'3': ObjectId('669a0268bb5b4fc21146b7a3'),
'4': ObjectId('669a0268bb5b4fc21146b7a4'),
'5': ObjectId('669a0268bb5b4fc21146b7a5'),
'6': ObjectId('669a0268bb5b4fc21146b7a6')
}}
Output:
[
{},
{},
{},
{ name: 'abc', age: 25 },
{ name: 'abc', age: 25 },
{ name: 'ghj', age: 55 },
{ name: 'cvb', age: 52 },
{ name: 'yhn', age: 80 },
{ name: 'wsg', age: 18 },
{ name: 'jhc', age: 29 },
{ name: 'jhc', age: 29 }
]
IV SEM MONGO DB LAB MANUAL DEPT Of AIML
b. Develop a MongoDB query to display the first 5 documents from the results
obtained in a. [use of limit and find]
Output:
[
{
_id: ObjectId('669a0268bb5b4fc21146b7a1'),
name: 'ghj',
age: 55,
gender: 'male'
},
{
_id: ObjectId('669a0268bb5b4fc21146b7a2'),
name: 'cvb',
age: 52,
gender: 'female'
},
{
_id: ObjectId('669a0268bb5b4fc21146b7a3'),
name: 'yhn',
age: 80,
gender: 'female'
}
]
Logical selectors
gender: 'male'
},
{
_id: ObjectId('669a0268bb5b4fc21146b7a6'),
name: 'jhc',
age: 29,
gender: 'male'
}
]
B. Execute query selectors (Geospatial selectors, Bitwise selectors ) and list outthe
results on any collection
use geospatialDB
db.createCollection("locations")
db.locations.insertMany([
{
name: "Location A",
location: {
type: "Point",
coordinates: [ -73.97, 40.77 ]
}
}
{
name: "Location B",
location: {
type: "Point",
coordinates: [ -73.88, 40.78 ]
}
}
])
Output:
[
{
_id: ObjectId('66575a5442058b31e6cdcdf8'),
name: 'location A',
location: { type: 'Point', coordinates: [ -73.97, 40.77 ] }
}
]
Bitwise selectors:
B.2
db.collection.insertMany([
{ "_id": 1, "field": 5 }, // binary: 0101
{ "_id": 2, "field": 9 }, // binary: 1001
{ "_id": 3, "field": 12 } // binary: 1100
])
4 Create and demonstrate how projection operators ($, $elematch and $slice) would be
used in the MondoDB.
db.marklist.insertMany([
{ "_id": 1, "semester": 1, "grades": [70, 87, 90] },
{ "_id": 2, "semester": 1, "grades": [90, 88, 92] },
{ "_id": 3, "semester": 1, "grades": [85, 100, 90] },
{ "_id": 4, "semester": 2, "grades": [79, 85, 80] },
{ "_id": 5, "semester": 2, "grades": [88, 88, 92] },
{ "_id": 6, "semester": 2, "grades": [95, 90, 96] }])
Query:
[
{ _id: 3, semester: 1, grades: [ 85, 100, 90 ] },
{ _id: 6, semester: 2, grades: [ 95, 90, 96 ] }
]
4) db.marklist.find({},{"grades": {"$slice": 1 } })
output:
{ _id: 1, semester: 1, grades: [ 70 ] },
{ _id: 2, semester: 1, grades: [ 90 ] },
{ _id: 3, semester: 1, grades: [ 85 ] },
{ _id: 4, semester: 2, grades: [ 79 ] },
{ _id: 5, semester: 2, grades: [ 88 ] },
{ _id: 6, semester: 2, grades: [ 95 ] }
IV SEM MONGO DB LAB MANUAL DEPT Of AIML
db.sales.insertMany([
{ "_id" : 1, "item" : "abc", "price" : 10, "quantity" : 2, "date" : ISODate("2014-01-
01T08:00:00Z") }
{ "_id" : 2, "item" : "jkl", "price" : 20, "quantity" : 1, "date" : ISODate("2014-02-
03T09:00:00Z") }
{ "_id" : 3, "item" : "xyz", "price" : 5, "quantity" : 5, "date" : ISODate("2014-02-
03T09:05:00Z") }
{ "_id" : 4, "item" : "abc", "price" : 10, "quantity" : 10, "date" : ISODate("2014-02-
15T08:00:00Z") }
{ "_id" : 5, "item" : "xyz", "price" : 5, "quantity" : 10, "date" : ISODate("2014-02-
15T09:05:00Z") }
{ "_id" : 6, "item" : "xyz", "price" : 5, "quantity" : 5, "date" : ISODate("2014-02-
15T12:05:10Z") }
{ "_id" : 7, "item" : "xyz", "price" : 5, "quantity" : 10, "date" : ISODate("2014-02-
15T14:12:12Z") }])
1.$avg:
db.sales.aggregate([
{
$group : {
_id : null,
averageQuantity: { $avg: "$quantity" },
count: { $sum: 1 }
}
}
])
Output:
2.$min.
output:
[ { _id: null, minqty: 1 } ]
IV SEM MONGO DB LAB MANUAL DEPT Of AIML
3.$max:
Output:
[ { _id: null, maxqty: 20 } ]
4.$push:
db.sales.aggregate(
[
{
$group:
{
_id: { day: { $dayOfYear: "$date"}, year: { $year: "$date" } },
itemsSold: { $push: { item: "$item", quantity: "$quantity" } }
}
}
]
output:
{
"_id" : { "day" : 34, "year" : 2014 },
"itemsSold" : [
{ "item" : "jkl", "quantity" : 1 },
{ "item" : "xyz", "quantity" : 5 }
]
}
{
"_id" : { "day" : 1, "year" : 2014 },
"itemsSold" : [ { "item" : "abc", "quantity" : 2 } ]
}
IV SEM MONGO DB LAB MANUAL DEPT Of AIML
5. )$addToSet
db.sales.aggregate(
[
{
$group:
{
_id: { day: { $dayOfYear: "$date"}, year: { $year: "$date" } },
itemsSold: { $addToSet: "$item" }
}
}
]
)
output:
6 Execute Aggregation Pipeline and its operations (pipeline must contain $match,
$group, $sort, $project, $skip etc. students encourage to execute several queries to
demonstrate various aggregation operators)
db.orders.insertMany( [
{ _id: 0, name: "Pepperoni", size: "small", price: 19, quantity: 10, date: ISODate(
"2021-03-13T08:14:30Z" ) },
{ _id: 1, name: "Pepperoni", size: "medium", price: 20, quantity: 20, date : ISODate(
"2021-03-13T09:13:24Z" ) },
{ _id: 2, name: "Pepperoni", size: "large", price: 21, quantity: 30, date : ISODate(
"2021-03-17T09:22:12Z" ) },
{ _id: 3, name: "Cheese", size: "small", price: 12, quantity: 15, date : ISODate( "2021-
03-13T11:21:39:36Z" ) },
{ _id: 4, name: "Cheese", size: "medium", price: 13, quantity:50, date : ISODate(
"2022-01-12T21:23:13.331Z" ) },
{ _id: 5, name: "Cheese", size: "large", price: 14, quantity: 10, date : ISODate( "2022-
01-12T05:08:13Z" ) },
{ _id: 6, name: "Vegan", size: "small", price: 17, quantity: 10, date : ISODate( "2021-
01-13T05:08:13Z" ) },
{ _id: 7, name: "Vegan", size: "medium", price: 18, quantity: 10, date : ISODate(
"2021-01-13T05:10:13Z" ) }] )
$sort:
db.restaurants.insertMany( [
{ "_id" : 1, "name" : "Central Park Cafe", "borough" : "Manhattan"},
{ "_id" : 2, "name" : "Rock A Feller Bar and Grill", "borough" : "Queens"},
{ "_id" : 3, "name" : "Empire State Pub", "borough" : "Brooklyn"},
{ "_id" : 4, "name" : "Stan's Pizzaria", "borough" : "Manhattan"},
{ "_id" : 5, "name" : "Jane's Deli", "borough" : "Brooklyn"},
])
Output:
$project:
db.restaurants.aggregate([{$project:{name:1}}])
output:
[
{ _id: 1, name: 'Central Park Cafe' },
{ _id: 2, name: 'Rock A Feller Bar and Grill' },
{ _id: 3, name: 'Empire State Pub' },
{ _id: 4, name: "Stan's Pizzaria" },
{ _id: 5, name: "Jane's Deli" }
]
Skip:
db.restaurants.aggregate([{ $skip : 2 }]);
output:
[
{ _id: 3, name: 'Empire State Pub', borough: 'Brooklyn' },
{ _id: 4, name: "Stan's Pizzaria", borough: 'Manhattan' },
{ _id: 5, name: "Jane's Deli", borough: 'Brooklyn' }
]
IV SEM MONGO DB LAB MANUAL DEPT Of AIML
7 a. Find all listings with listing_url, name, address, host_picture_url in the listings
And Reviews collection that have a host with a picture url
Inserting values:
db.listings_and_reviews.insertMany([
{
listing_url: "https://example.com/listing/2",
name: "Cozy Cabin",
address: "456 Forest Rd, City, Country",
host: {
picture_url: "https://example.com/host/2.jpg"
}
},
{
listing_url: "https://example.com/listing/3",
name: "Modern Loft",
address: "789 Skyline Dr, City, Country",
host: {
picture_url: "https://example.com/host/3.jpg"
}
}
])
QUERY:
db.listings_and_reviews.find(
{ "host.picture_url": { $exists: true, $ne: null, $ne: "" } },
{
"listing_url": 1,
"name": 1,
"address": 1,
"host.picture_url": 1
}
)
IV SEM MONGO DB LAB MANUAL DEPT Of AIML
Output:
[
{
_id: ObjectId('665ff9827f1e6a6c00cdcdf6'),
listing_url: 'https://example.com/listing/2',
name: 'Cozy Cabin',
address: '456 Forest Rd, City, Country',
host: { picture_url: 'https://example.com/host/2.jpg' }
},
{
_id: ObjectId('665ff9827f1e6a6c00cdcdf7'),
listing_url: 'https://example.com/listing/3',
name: 'Modern Loft',
address: '789 Skyline Dr, City, Country',
host: { picture_url: 'https://example.com/host/3.jpg' }
},
{
_id: ObjectId('6660027c22c200c983cdcdf6'),
listing_url: 'https://example.com/listing/2',
name: 'Cozy Cabin',
address: '456 Forest Rd, City, Country',
host: { picture_url: 'https://example.com/host/2.jpg' }
},
{
_id: ObjectId('6660027c22c200c983cdcdf7'),
listing_url: 'https://example.com/listing/3',
name: 'Modern Loft',
address: '789 Skyline Dr, City, Country',
host: { picture_url: 'https://example.com/host/3.jpg' }
}
]
IV SEM MONGO DB LAB MANUAL DEPT Of AIML
{
product_name: "Product B",
reviews: [
{
rating: 3,
comment: "Average product.",
date: new Date("2023-02-20")
},
{
rating: 2,
comment: "Not satisfied with the quality.",
date: new Date("2023-04-05")
}
]
},
{
product_name: "Product C",
reviews: [
{
rating: 5,
comment: "Highly recommend!",
date: new Date("2023-05-18")
}
]
}
])
IV SEM MONGO DB LAB MANUAL DEPT Of AIML
Query:
db.ecommerce.aggregate([
{ $unwind: "$reviews" }, // Deconstruct the reviews array
{
$group: {
_id: null,
totalReviews: { $sum: 1 }, // Count total number of reviews
averageRating: { $avg: "$reviews.rating" }, // Calculate average rating
latestReview: { $max: "$reviews.date" }, // Find the most recent review date
oldestReview: { $min: "$reviews.date" } // Find the oldest review date
}
},
{
$project: {
_id: 0, // Exclude the _id field from the results
totalReviews: 1,
averageRating: 1,
latestReview: 1,
oldestReview: 1
}
}
])
Output:
[
{
totalReviews: 5,
averageRating: 3,
latestReview: ISODate('2023-07-05T00:00:00.000Z'),
oldestReview: ISODate('2023-01-15T00:00:00.000Z')
}
]
IV SEM MONGO DB LAB MANUAL DEPT Of AIML
synatax:
db.exampleCollection.createIndex({ "fieldName": 1 }, { unique: true })
Query:
db.exampleCollection.insertMany([
{ _id: 1, username: "alice", age: 25 },
{ _id: 2, username: "bob", age: 30 }
]);
2. Sparse Index
A sparse index only indexes the documents that contain the indexed field,
skipping documents that do not have the field.
synatax:
db.exampleCollection.createIndex({ "fieldName": 1 }, { sparse: true })
Query:
db.exampleCollection.insertMany([
{ _id: 3, username: "carol" },
{ _id: 4, username: "dave", email: "[email protected]" }
]);
synatax:
db.exampleCollection.createIndex({ "field1": 1, "field2": -1 })
Query:
db.exampleCollection.insertMany([
{ _id: 5, firstName: "eve", lastName: "johnson" },
{ _id: 6, firstName: "frank", lastName: "smith" }
IV SEM MONGO DB LAB MANUAL DEPT Of AIML
]);
synatax:
db.exampleCollection.createIndex({ "arrayField": 1 })
Query:
db.exampleCollection.insertMany([
{ _id: 7, tags: ["mongodb", "database", "nosql"] },
{ _id: 8, tags: ["indexing", "performance"] }
]);
Unique Index:
db.optimization.createIndex({ "name": 1 }, { unique: true });
Compound Index:
db.exampleCollection.createIndex({ name: 1, age: 1 });
Multiple Index:
db.exampleCollection.createIndex({ tags: 1 });
Output:
Output:
email_1
IV SEM MONGO DB LAB MANUAL DEPT Of AIML
use catalogDB
db.catalog.insertMany
([ { title: "Data Science for Beginners", description: "An introductory book on data
science." },
{ title: "Advanced Machine Learning", description: "A deep dive into machine learning
algorithms." },
{ title: "MongoDB in Action", description: "A comprehensive guide to MongoDB." }, {
title: "Data Analysis with Python", description: "Learn data analysis techniques using
Python." },
{ title: "Introduction to Big Data", description: "Basics of big data technologies." } ])
Output:
[
{
_id: ObjectId('667fb027b7d7b34e21cdcdfa'),
title: 'Introduction to Big Data',
description: 'Basics of big data technologies.'
},
{
_id: ObjectId('667fb027b7d7b34e21cdcdf6'),
title: 'Data Science for Beginners',
description: 'An introductory book on data science.'
},
{
_id: ObjectId('667fb027b7d7b34e21cdcdf9'),
title: 'Data Analysis with Python',
description: 'Learn data analysis techniques using Python.'
}
]
IV SEM MONGO DB LAB MANUAL DEPT Of AIML
Method:1
db.catalog.aggregate([
{ $match: { $text: { $search: "data" } } },
{ $match: { title: { $not: /Python/ }, description: { $not: /Python/ } } }
])
Method:2
db.catalog.aggregate([
{ $match: { $text: { $search: "data" } } },
{ $match: {
$and: [
{ title: { $not: /Python/ } },
{ description: { $not: /Python/ } }
]
}}
])
Output:
[
{
_id: ObjectId('667fb027b7d7b34e21cdcdfa'),
title: 'Introduction to Big Data',
description: 'Basics of big data technologies.'
},
{
_id: ObjectId('667fb027b7d7b34e21cdcdf6'),
title: 'Data Science for Beginners',
description: 'An introductory book on data science.'
}
]
10 Develop an aggregation pipeline to illustrate Text search on Catalog data collection.
db.catalog.aggregate([
{
$match: {
$text: { $search: "data" }
}
},
{
$match: {
$and: [
{ title: { $not: /Python/ } },
IV SEM MONGO DB LAB MANUAL DEPT Of AIML
Output:
[
{
_id: ObjectId('667fb027b7d7b34e21cdcdfa'),
title: 'Introduction to Big Data',
description: 'Basics of big data technologies.',
score: 1.2916666666666665
},
{
_id: ObjectId('667fb027b7d7b34e21cdcdf6'),
title: 'Data Science for Beginners',
description: 'An introductory book on data science.',
score: 1.2916666666666665
}
]