Skip to content

Instantly share code, notes, and snippets.

@Anna-Myzukina
Last active December 3, 2021 15:18
Show Gist options
  • Save Anna-Myzukina/77bed345291007fbb0791d358fbad563 to your computer and use it in GitHub Desktop.
Save Anna-Myzukina/77bed345291007fbb0791d358fbad563 to your computer and use it in GitHub Desktop.
learnyoumongodb

//Exercise 1 Install mongodb from:

  1. https://www.mongodb.org/downloads. or sudo apt install mongodb

To verify that mongod is installed, you can try running mongod --version

//Exercise 2 Start mongod on port 27017 with data as the dbpath 1.at first terminal : mkdir data , next cd data , next mongod --port 27017 --dbpath=./data 2.at onother terminal run npm install mongodb

//Exercise 3
/*learn how to search for documents.
In this exercise the database name is learnyoumongo.
So, the url would be something like: mongodb://localhost:27017/learnyoumongo
Use the parrots collection to find all documents where age
is greater than the first argument passed to your script.
Using console.log, print the documents to stdout
*/
var mongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/learnyoumongo';
var age = parseInt(process.argv[2]);
mongoClient.connect(url, function(err, db) {
let dataBase = db.db('learnyoumongo');
if (err) {
console.log('Error connecting');
}
dataBase.collection('parrots')
.find({ age: { $gt: +age } })
.toArray(function(err, documents) {
if (err) {
console.log('Error reading')
}
console.log(documents);
db.close();
});
});
// Exercise 4
/*Use the parrots collection from the database named learnyoumongo to
find all documents where age is greater than the first argument
passed to your script.
Using console.log, print the documents to stdout
*/
var mongo = require('mongodb').MongoClient;
var age = process.argv[2];
var url = 'mongodb://localhost:27017/learnyoumongo';
mongo.connect(url, function(err, db) {
if (err) throw err;
db.collection('parrots')
.find({age: {$gt: +age} },
{name: 1,
age: 1,
_id: 0})
.toArray(function(err, documents) {
if (err) {
console.log('Error reading')
}
console.log(documents);
db.close();
});
})
//Exercise 5
/*Connect to MongoDB on port 27017.
You should connect to the database named learnyoumongo and insert
a document into the docs collection.
The document should be a json document with the following properties:
* `firstName`
* `lastName`
firstName will be passed as the first argument to the lesson.
lastName will be passed as the second argument to the lesson.
Use console.log to print out the object used to create the document.
Make sure you use JSON.stringify convert it to JSON
*/
var mongo = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/learnyoumongo';
var firstName = process.argv[2];
var lastName = process.argv[3];
var doc = {
firstName: firstName,
lastName: lastName
};
mongo.connect(url, function(err, db) {
if (err) throw err;
var users = db.collection('users');
users.insert(doc, function(err, data) {
if (err) throw err;
console.log(JSON.stringify(doc));
db.close();
})
})
//Exercise 6
/*Here we are going to update a document in the users collection.
The database name will be accessible via process.argv[2].
Say we have a user defined like:
{
"name": "Tina",
"age": 30,
"username": "tinatime"
}
We want to change Tina's age from 30 to 40.
For the purpose of this lesson, assume that the username property is unique.
*/
var mongo = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/' + process.argv[2];
mongo.connect(url, function(err, db) {
if (err) throw err;
var users = db.collection('users');
users.update({
username: 'tinatime'
}, {$set: {age: 40 } },
function(err) {
if (err) throw err;
db.close();
})
})
//Exercise 7
/*This lesson involves removing a document with the given _id.
The database name will be accessible via process.argv[2].
The collection name will be passed as the second argument to your script.
The _id will be passed as the third argument to your script.
*/
var mongo = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/' + process.argv[2];
mongo.connect(url, function(err, db) {
var collection = db.collection(process.argv[3]);
var _id = process.argv[4];
collection.remove({_id: _id},
function(err) {
if (err) throw err;
db.close();
})
})
//Exercise 8
/*Here we will learn how to count the number of documents that
meet certain criteria.
Use the parrots collection from the database named learnyoumongo to
count all documents where age is greater than the first argument
passed to your script.
Using console.log, print the number to stdout.
*/
var mongoClient = require('mongodb').MongoClient;
var collectionName = 'parrots';
var databaseName = 'learnyoumongo';
var url = 'mongodb://localhost:27017/learnyoumongo';
var age = process.argv[2];
mongoClient.connect(url, function(err, DB) {
var dataBase = DB.db(databaseName);
dataBase.collection(collectionName)
.count({ age: { $gt: +age } })
.then(console.log)
.catch(console.log);
DB.close();
})
//Exercise 9
/*Aggregation allows one to do things like
calculate the sum of a field of multiple documents or the average
of a field of documents meeting particular criteria.
Say you have a collection named prices. Each price document is modeled
like so:
{
"name": "Tshirt",
"size": "S",
"price": 10,
"quantity": 12
"meta": {
"vendor": "hanes",
"location": "US"
}
}
In this exercise, we need to calculate the average price for all documents
in the prices collection in the database named learnyoumongo that have
the size that will be passed as the first argument to your script.
Use console.log() to print the average price rounded to 2 decimal places
to stdout after you have found it.
*/
var mongoClient = require('mongodb').MongoClient;
var collectionName = 'prices';
var databaseName = 'learnyoumongo';
var size = process.argv[2];
var url = 'mongodb://localhost:27017/learnyoumongo';
mongoClient.connect(url, function(err, DB) {
var dataBase = DB.db(databaseName);
dataBase.collection(collectionName)
.aggregate([
{ $match: { size: size } },
{ $group: {_id: 'average',
total: { $avg: '$price' }
} }])
.toArray(function(err, results) {
if (err) {
console.log(err);
}
if (!results.length) {
throw new Error('No results found')
}
console.log(Number(results[0].total).toFixed(2));
});
DB.close();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment