Monthly Archives

September 2021

MongoDB | Index

By | MongoDB Learning

To get index lists

db.tableName.getIndexes()

To set Index

db.contact.createIndex({age:1})

It will create index in asc order

db.contact.createIndex({age:-1})

It will create index in desc order

db.contact.createIndex({age:1, gender:1})

Create group of index with age and gender both done in asc order.


To Delete Index

db.contact.dropIndex({"age": 1})

Value of key need to be 1 or -1 based on how index was created. If asc, 1 and for desc it is -1


Create Unique index

db.contact.createIndex({email:1},{unique: true})

Create Unique Index on email field. While inserting data one have to provide email field, else it would throw error

db.users.createIndex({email: 1}, {unique: true, partialFilterExpression: {email: {$exists: true}}})

Only create index for email field if exists. If field doesn't exists, no issue even while inserting new data.


TTL Index

db.sessions.createIndex({createdAt: 1}, {expireAfterSeconds: 10})

create index for CreatedAt (the column should be datetime type) and destroy the record having that index after 10 seconds.

MongoDB | Advanced Update Operators

By | MongoDB Learning
db.users.updateOne({"_id" : ObjectId("11a")}, {$inc: {age: 2}})

Increment age by 2 for object id 11a


db.users.updateOne({"_id" : ObjectId("11a")}, {$inc: {age: -1}, $set: {exp: 22}})

Decrement age by 1 for object id 11a and set exp = 22


let assume a user Chris has age of 35

db.users.updateOne({name: "Chris"}, {$min: {age: 32}})

If age is more than 32, set age to 32. Chris age will change to 32

db.users.updateOne({name: "Chris"}, {$max: {age: 38}})

If age is less than 38, set age to 38. Chris age will change to 38 (as it was set to 32).


db.users.updateOne({name: "Chris"}, {$mul: {age: 1.1}})

Multiply age by 1.1


db.users.updateMany({isSporty: true}, {$unset: {phone: ""}})

Unset a field name phone. Need to provide an empty value to get it work.


db.users.updateMany({}, {$rename: {name: "FullName", age: "TotalAge"}})

Rename field named name to Full Name and age to Total Age.


db.users.updateOne({name: "Maria"}, {$set: {age: 26, hobbies: [{title: "Good food", frequency: 1}], isSporty: true}}, {upsert: true})

upsert as third param(Can be read as update or insert), can insert if not found, or if found it will update the value.

In above example, it will search for name Maria, if it exists it will update rest of the values, if it doesn't exisits, the new record will be created.


db.users.updateOne({name: "Maria"}, {$push: {hobbies: {title: "Sports", frequency: 2}}})

Push element with value if value exists, it will still add another element.


db.users.updateOne({name: "Maria"}, {$pull: {hobbies: {title: "Sports"}}})

Pull/Remove the element named Sports from hobbies


db.users.updateOne({name: "Maria"}, {$addToSet: {hobbies: {title: "Sports", frequency: 2}}})

Add element with value if value exists, it will not add add another element if value of the element is same. This is useful to avoid duplicate entry.


MongoDB | Update Operators

By | MongoDB Learning

Fields

NameDescription
$currentDateSets the value of a field to current date, either as a Date or a Timestamp.
$incIncrements the value of the field by the specified amount.
$minOnly updates the field if the specified value is less than the existing field value.
$maxOnly updates the field if the specified value is greater than the existing field value.
$mulMultiplies the value of the field by the specified amount.
$renameRenames a field.
$setSets the value of a field in a document.
$setOnInsertSets the value of a field if an update results in an insert of a document. Has no effect on update operations that modify existing documents.
$unsetRemoves the specified field from a document.

Array

Operators

NameDescription
$Acts as a placeholder to update the first element that matches the query condition.
$[]Acts as a placeholder to update all elements in an array for the documents that match the query condition.
$[<identifier>]Acts as a placeholder to update all elements that match the arrayFilters condition for the documents that match the query condition.
$addToSetAdds elements to an array only if they do not already exist in the set.
$popRemoves the first or last item of an array.
$pullRemoves all array elements that match a specified query.
$pushAdds an item to an array.
$pullAllRemoves all matching values from an array.

Modifiers

NameDescription
$eachModifies the $push and $addToSet operators to append multiple items for array updates.
$positionModifies the $push operator to specify the position in the array to add elements.
$sliceModifies the $push operator to limit the size of updated arrays.
$sortModifies the $push operator to reorder documents stored in an array.

Bitwise

NameDescription
$bitPerforms bitwise AND, OR, and XOR updates of integer values.

MongoDB | Advanced Read Operations

By | MongoDB Learning
db.users.find({}).sort({id: 1}).pretty()

.sort() with id in acending order

db.users.find({}).sort({id: -1}).pretty()

.sort() with id in decending order

db.users.find({}).sort({"ratings.average": -1}).pretty()

.sort() filter applied on average doocument/element under ratings with decending order

db.users.find({}).sort({"ratings.average": 1},{runtime: -1}).pretty()

.sort() in acending order by average ratings followed by runtime in decending order. eg. result will be like:

1) avgrating: 2, runtime 60 
2) avgrating: 2, runtime 40 
3) avgrating: 2, runtime 20 
4) avgrating: 4.1, runtime 60 
5) avgrating: 5, runtime 50 
6) avgrating: 5, runtime 40 
7) avgrating: 7.1, runtime 60

db.movies.find({}, {name: 1, _id: 0, "rating.average": 1, runtime: 1}).skip(10)

Skip first 10 result and show all result after 10th record

db.movies.find({}, {name: 1, _id: 0, "rating.average": 1, runtime: 1}).skip(100).limit(10)

Skip first 10 result and limit result to 10.


db.MoviesCollection.find({}, {genres: {$slice: 2}}).pretty()

Find all document but return only first two elements of genres in the result set.

db.MoviesCollection.find({}, {genres: {$slice: [1, 2]}}).pretty()

Find all document but return by skipping first element and display rest two elements of genres in the result set.