Skip to content

Instantly share code, notes, and snippets.

@heytulsiprasad
Last active July 14, 2020 08:31
Show Gist options
  • Select an option

  • Save heytulsiprasad/f10d4fb9709b9b023186e640614699c0 to your computer and use it in GitHub Desktop.

Select an option

Save heytulsiprasad/f10d4fb9709b9b023186e640614699c0 to your computer and use it in GitHub Desktop.
Notes on MongoDB

Making less costly queries

As an example, when we write db.students.find() and then do a forEach() loop over it, we are increasing the cost of the process as what we're doing is:

  • Fetching all students from to server
  • Running forEach on our server to filter data we need

To avoid getting uncessary data and decrease the load on our server we can do requests specific to our needs, like these.

db.students.find({}, {name: 1, email: 0}) # values with 1 show up, 0 don't
db.students.find({}, {_id: 1, email: 1}).toArray # returns data in an array

Extra: To print the data in shell while looping over it, db.students.find().forEach((stu) => {printjson(stu)})

Nest a level deep inside objects

We can find data specific to our requirement using a (.) operator in our document, like:

db.students.find({"profilePic.medium": { $gt: 90 }})

Chain query strings

We can do this: ✅

db.students.findOne({ name: "Mark" }).lastLogin

But cannot do this: ❌

db.students.find({ name: "Mark" }).lastLogin

Schema is the basic structure we give to our any collection (or table) in our database.

Sure, we can definitely add more keys to this later, but we need to have a basic defining structure for us to avoid any reassigning of key names and such conflicts.

Making Relations

We make relations by passing _id of other objects or secondary collections (or tables) to our primary collection.

  • One to One
  • One to Many
  • Many to Many
[
{
"name": "Alex",
"email": "alex@gmail.com",
"contact": "992022331",
"courseCount": "3",
"isVerified": "true"
},
{
"name": "Mark",
"email": "mark@gmail.com",
"contact": "1235476864",
"courseCount": "19",
"isVerified": "false",
"profilePic" : {
"small" : 50,
"medium" : 100,
"big" : 200,
"large" : 500
},
"lastLogin" : [
"Mon",
"Tue",
"Wed"
]
}
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment