MongoDB Cheat Sheet

MongoDB is a source-available cross-platform document-oriented database program. Classified as a NoSQL database program, MongoDB uses JSON-like documents with optional schemas.

to start server (mongod is mongo deamon)

mongod

to start shell

mongo
show dbs;
create/use database

Change database

use db_name;

show current database

db;

Collections are similar to table

show collections;
db.createCollection("students");

Drop collection/table

db.students.drop();

drop database

db.dropDatabase();

insertOne

db.students.insertOne({_id: 1, name: "shailesh"});

insertMany

db.students.insertMany([{_id: 2, name: "bagde"}, {_id: 3, name: "sheldon"}]);

count document

db.students.count();

select all documents/records

db.students.find();

select with projection

db.students.find({},{_id: 0});
db.students.find({},{name:0});

exists operator

db.students.find({age: {$exists: false}});

COMPARISON OPERATORS

in operator

db.students.find({_id: {$in: [2,3]}});

not equal operator

db.students.find({_id: {$ne: 2}});

equal operator

db.students.find({_id: {$eq: 2}});

less than $lt

less than equal $lte

greather than $gt

greater than equal $gte

LOGICAL OPERATORS

$and operator

db.students.find({$and : [{_id : {$gt:1}}, {_id: {$lt: 4}}]})

$or operator

db.students.find({$or : [{name : "bagde"}, {name: "shailesh"}]})

like case insensitive

db.students.find({name: /h/i})

exact match

db.students.find({name: /^BagDe$/i})

UPDATE

db.students.updateOne({_id: 1}, {$set : {age: 23}});
db.students.updateMany({age : {$exists: false}}, { $set : {age : 25}})
db.students.updateMany({}, {$set: {address: {city: "Mumbai", state: "MH"}}})
db.students.updateOne({_id: 4}, { $set : {address : {city: "Nagpur"}}});

Unset/Delete Fields

db.students.updateMany({}, {$unset : {city: ""}});

search within sub document

db.students.find({"address.city" : "Nagpur"}).pretty();

Delete Records

db.students.deleteOne({ $or : [{ age : {$lt : 25}}, {name : "sheldon"}] })

DISTINCT

db.students.distinct(“city”)

ORDER BY

db.students.find().sort({name: -1})

LIMIT

db.students.find().limit(10)
db.students.find().skip(5).limit(10)

Aggregation

Aggregate on all documents
db.emps.aggregate([{$group: {
	_id : null,
	total : {$sum : "$salary"},
	average : {$avg: "$salary"},
	min : {$min: "$salary"},
	max : {$max: "$salary"},
	count : {$sum: 1}	
}}]).pretty()


Aggregate on group by address
db.emps.aggregate([{$group: {
	_id : { address: "$address" },
	total : {$sum : "$salary"},
	average : {$avg: "$salary"},
	min : {$min: "$salary"},
	max : {$max: "$salary"},
	count : {$sum: 1}	
}}]).pretty()

ForEach Map

db.emps.find().forEach(x => { print(x.name) })

db.emps.find({salary: { $exists: -1 } }, {"salary": 1, _id: 0}).map(x => x.salary * 0.10)

MongoDB Assignment for Practice

var docs = [
{"name":"neha","contact_number":"9833910534","address":"mumbai","salary":30000,"employee_id":98821,"role":"manager"},
{"name":"mina","contact_number":"9833910535","address":"thane","salary":32000,"employee_id":98823,"role":"sales"},
{"name":"pankaj","contact_number":"9833910536","address":"bhopal","salary":40000,"employee_id":98824,"role":"hr"},
{"name":"mareena","contact_number":"9833910537","address":"meerut","salary":45000,"employee_id":98825,"role":"support"},
{"name":"pooja","contact_number":"9833910538","address":"delhi","salary":50000,"employee_id":98826,"role":"developer"},
{"name":"namita","contact_number":"9833910539","address":"surat","salary":52000,"employee_id":98820,"role":"sales"},
{"name":"sneha","contact_number":"9833910510","address":"baroda","salary":55000,"employee_id":98827,"role":"support"},
{"name":"anjali","contact_number":"9833910511","address":"ahmedabad","salary":60000,"employee_id":98828,"role":"tester"},
{"name":"harsha","contact_number":"9833910512","address":"mumbai","salary":20000,"employee_id":98829,"role":"operations"},
{"name":"varun","contact_number":"9833910512","address":"mehsana","salary":56000,"employee_id":98831,"role":"tester"},
{"name":"preeti","contact_number":"9833910513","address":"noida","salary":87000,"employee_id":98832,"role":"developer"},
{"name":"madhu","contact_number":"9833910525","address":"bangalore","salary":22000,"employee_id":98833,"role":"sales"}
];

db.createCollection("emps");
db.emps.insertMany(docs);
db.emps.find();

var docs = [{“name”:”neha”,”contact_number”:”9833910534″,”address”:”mumbai”,”salary”:30000,”employee_id”:98821,”role”:”manager”},{“name”:”mina”,”contact_number”:”9833910535″,”address”:”thane”,”salary”:32000,”employee_id”:98823,”role”:”sales”},{“name”:”pankaj”,”contact_number”:”9833910536″,”address”:”bhopal”,”salary”:40000,”employee_id”:98824,”role”:”hr”},{“name”:”mareena”,”contact_number”:”9833910537″,”address”:”meerut”,”salary”:45000,”employee_id”:98825,”role”:”support”},{“name”:”pooja”,”contact_number”:”9833910538″,”address”:”delhi”,”salary”:50000,”employee_id”:98826,”role”:”developer”},{“name”:”namita”,”contact_number”:”9833910539″,”address”:”surat”,”salary”:52000,”employee_id”:98820,”role”:”sales”},{“name”:”sneha”,”contact_number”:”9833910510″,”address”:”baroda”,”salary”:55000,”employee_id”:98827,”role”:”support”},{“name”:”anjali”,”contact_number”:”9833910511″,”address”:”ahmedabad”,”salary”:60000,”employee_id”:98828,”role”:”tester”},{“name”:”harsha”,”contact_number”:”9833910512″,”address”:”mumbai”,”salary”:20000,”employee_id”:98829,”role”:”operations”},{“name”:”varun”,”contact_number”:”9833910512″,”address”:”mehsana”,”salary”:56000,”employee_id”:98831,”role”:”tester”},{“name”:”preeti”,”contact_number”:”9833910513″,”address”:”noida”,”salary”:87000,”employee_id”:98832,”role”:”developer”},{“name”:”madhu”,”contact_number”:”9833910525″,”address”:”bangalore”,”salary”:22000,”employee_id”:98833,”role”:”sales”}];

  1. show employees in descending order – salary
  2. show all employees from Mumbai
  3. show all employees having salary more 50000
  4. show sum of salary from emps collection
  5. show all distinct address
  6. show names of employees having max salary
  7. show employees having 2nd highest salary
  8. count employees from mumbai only
  9. show all female employees
  10. show all male employees

1,381 Replies to “MongoDB Cheat Sheet”

  1. Недропользование — это совокупность процессов, связанный с освоением природных ресурсов.
    Оно включает разведку природных ресурсов и их дальнейшую переработку.
    Недропользование регулируется законодательством, направленными на безопасность работ.
    Эффективное управление в недропользовании обеспечивает устойчивое развитие.
    оэрн

  2. Выполнение домашних заданий имеет большое значение в учебной деятельности.
    Домашняя работа способствует усвоить материал и лучше понять темы.
    Со временем ученики развивают дисциплину.
    Регулярные задания помогают научиться грамотно распределять нагрузку.
    https://encl22.ru
    Кроме того, домашняя работа способствует развитию самостоятельное мышление.
    Школьники чувствуют себя спокойными на контрольных работах.
    Постепенно выполнение заданий оказывает хорошее влияние на общую успеваемость.
    В результате домашние задания остаются неотъемлемым элементом школьного обучения.

  3. Hello friends!
    I came across a 153 fantastic site that I think you should browse.
    This site is packed with a lot of useful information that you might find valuable.
    It has everything you could possibly need, so be sure to give it a visit!
    https://idealbloghub.com/a-summary-of-unbeaten-football-betting-experiences-for-rookies/

    Additionally don’t forget, everyone, that you at all times are able to inside this article find responses for your most tangled inquiries. Our team made an effort to explain all of the content via an very understandable method.

  4. Нужен проектор? магазин проекторов в Москве большой выбор моделей для дома, офиса и бизнеса. Проекторы для кино, презентаций и обучения, официальная гарантия, консультации специалистов, гарантия качества и удобные условия покупки.

  5. Нужен проектор? projector24.ru большой выбор моделей для дома, офиса и бизнеса. Проекторы для кино, презентаций и обучения, официальная гарантия, консультации специалистов, гарантия качества и удобные условия покупки.

  6. Hello !!
    I came across a 153 interesting tool that I think you should visit.
    This resource is packed with a lot of useful information that you might find insightful.
    It has everything you could possibly need, so be sure to give it a visit!
    https://techtranche.com/the-three-unities-to-consider-in-the-case-of-betting/

    And don’t overlook, folks, that one constantly are able to inside this particular article locate solutions for your the absolute confusing queries. Our team made an effort to lay out all of the information in the very accessible manner.

  7. Лучшее казино upx играйте в слоты и live-казино без лишних сложностей. Простой вход, удобный интерфейс, стабильная платформа и широкий выбор игр для отдыха и развлечения.

  8. Лучшее казино upx играйте в слоты и live-казино без лишних сложностей. Простой вход, удобный интерфейс, стабильная платформа и широкий выбор игр для отдыха и развлечения.

  9. Продуманный внешний вид имеет большое значение в создании образа.
    Она дает возможность подчеркнуть индивидуальность.
    Удачный внешний вид усиливает самооценку.
    Одежда часто становится частью первого восприятия.
    https://blog.lasuper.ru/luisa-spagnoli/
    Кроме того, продуманный гардероб делает сборы быстрее в повседневных делах.
    Со временем внимание к стилю развивает вкус.
    Таким образом стильная одежда играет значимую роль современного образа жизни.

  10. Ответственная гемблинг — представляет собой набор строгих принципов и практик.
    Данная концепция ориентирована для обеспечение безопасности пользователей от рисков.
    Основная цель — сохранить развлекательную составляющую исключая ущерба для личного состояния человека.
    https://t.me/s/top_onlajn_kazino_rossii
    Данная практика включает контроль над длительностью и средствами, тратящимися на игру.
    Важным элементом служит осознание игроком всех потенциальных рисков.
    Платформы обязаны обеспечивать понятную сведения и инструменты с целью самоограничения.
    Таким образом, ответственная игра формирует безопасную игровую среду для каждого участников.

  11. Оформление ВНЖ за границей имеет большое значение.
    Оно предоставляет законную возможность на длительное проживание в выбранной стране.
    надувная кукла женщина купить в кредит
    Это гарантирует полный доступ к национальному медицинскому обслуживанию.
    Получение ВНЖ значительно облегчает процесс финансового обслуживания и открытия своего дела.
    В конечном счёте, это является важнейшим этапом к постоянному проживанию или возможно второму гражданству.

  12. Цифровая печать — наиболее популярный вид тиражной печати.
    Цифровая полиграфия отлично подходит для быстрых тиражей и персонализации.
    Трафаретная печать часто используется для нанесения на сувенирную продукцию и нестандартные материалы.
    https://odesli.co/printinghouse4z
    Флексография применяется в основном для гибкой упаковки и печати наклеек.
    Для внешней рекламы обычно заказывают крупноформатную печать на баннерах.
    Послепечатная доводка содержит такие операции, как ламинирование, тиснение и фальцовка.

  13. Gorilla Tag mods are fun to explore because they add new
    features.
    Some Gorilla Tag players use mods to customize their experience,
    especially in allowed modes.

    A number of mods change movement mechanics, while others
    focus on visuals.
    Some mods are quality-of-life focused that improve usability.

    Mod menus are often mentioned because they bundle multiple
    features into one system.
    Each menu is different, so choices vary by user.

    Using mods requires caution, and only in private rooms.

    Misusing mods can create problems for other players.

    The Gorilla Tag mod community is constantly evolving, with updated tools being shared often.

    Many creators maintain their projects to keep them compatible.

    As the game updates, certain mods need updates, so staying
    informed is recommended.
    Overall, mods expand options for the community, when used correctly.

  14. GT mods are really interesting because they add new features.

    Many players use mods to customize their experience, especially
    outside public matches.

    Certain mods improve mobility, while others focus on visuals.

    Utility-based mods exist that improve usability.

    Mod menus are commonly used because they include several tools into
    a single menu.
    Not all mod menus are the same, so players usually choose based on preference.

    Using mods requires caution, and only in private rooms.
    Using mods in public lobbies can cause issues.

    The Gorilla Tag mod community is growing over time, with new mods being released regularly.

    Many creators update their mods to fix bugs.

    When Gorilla Tag receives updates, certain mods need updates, so staying informed is
    important.
    Overall, mods expand options for curious players, when used correctly.

Leave a Reply to Johnslume Cancel reply

Your email address will not be published.