Explore topic-wise InterviewSolutions in Current Affairs.

This section includes 7 InterviewSolutions, each offering curated multiple-choice questions to sharpen your Current Affairs knowledge and support exam preparation. Choose a topic below to get started.

1.

Some other Handy commands

Answer»
  • use admin
db.createUser({"user": "major", "pwd": passwordPrompt(), "roles": ["major"]})
db.dropUser("major")
db.auth( "user", passwordPrompt() )
  • use test
db.getSiblingDB("dbname")
db.currentOp()
db.killOp(345) // opid
  • Change Streams
watchCursor = db.docx.watch( [ { $match : {"operationType" : "insert" } } ] )
while (!watchCursor.isExhausted()){
if (watchCursor.hasNext()){
print(tojson(watchCursor.next()));
}
}
  • Search in a MongoDb Database: 

db.comments.find({lang:'Python'})

  • Showing All Collections in a Database: 

db.getCollectionNames()

  • Listing a Collection’s Records: 

db.collectionname.find()

  • Listing Records with Matching Values of Specific Fields: 

db. collectionname.find({"field2": "secondmatching value"})

  • Multiple Matching Values:

db. collectionname.find({"field2": "second matching value", "field3": "thirdmatchingvalue"})

  • Finding a Single Record:

db. collectionname.findOne({"field2": "content"})

Conclusion

MongoDB is one of the world’s most popular document databases. It has some powerful capabilities like full-text search, data aggregation etc. One should have a solid knowledge of what MongoDB is. In this document, we’ve covered the basics of MongoDB, its features, and some of the important cheat sheets. We’ve also explored the common database operations of MongoDB. Now, it’s time for you to head out and try what we’ve covered here and more.

Useful Resources

  • Technical Interview Questions

  • Coding Interview Questions

  • Interview Resources

  • DSA- Programming

  • Mock Interview

  • MongoDB Vs MySQL


2.

Databases and Collections

Answer»


  • Drop: db.docx.drop()    // removes the collection and its index definitions

  • Create Collection:

// Create collection with a $jsonschema
db.createCollection("contacts", {
validator: {$jsonSchema: {
bsonType: "object",
required: ["gadget"],
properties: {
phone: {
bsonType: "string",
description: "must be a string and is required"
},
email: {
bsonType: "string",
pattern: "@mongodb\.com$",
description: "must be a string and match the regular expression pattern"
},
status: {
enum: [ "Unknown", "Incomplete" ],
description: "can only be one of the enum values"
}
}
}}
})

  • Other Collection Functions

    • In order to create a statistical structure and to copy a pointer into a user-specified memory location, use: db.docx.stats() 

    • The total amount of storage in bytes allocated to the document for document storage can be known by using: db.docx.storageSize()

    • To report the total size used by the indexes in a collection document, use: db.docx.totalIndexSize()

    • The total size in bytes of the data in the collection plus the size of every index can be known by using: db.docx.totalSize()



3.

Aggregation

Answer»
  1.  
OperatorDescriptionCommand
$sum Sum up values db.docx.aggregate([{$group : {_id : "$operator", num_docx : {$sum : "$value"}}}])
$avgCalculates average valuesdb.docx.aggregate([{$group : {_id : "$operator", num_docx : {$avg : "$value"}}}]) 
$min / $maxFind min/max valuesdb.docx.aggregate([{$group : {_id : "$operator", num_docx : {$min : "$value"}}}])
$push Push values to a result array db.docx.aggregate([{$group : {_id : "$operator", classes : {$push: "$value"}}}])
$addToSet Push values to a result array without duplicates db.docx.aggregate([{$group : {_id : "$operator", classes : {$addToSet : "$value"}}}]) 
$first / $last To get the first / last document db.docx.aggregate([{$group : {_id : "$operator", last_class : {$last : "$value"}}}])

4.

Indexes

Answer»


  • List Indexes: It can be done by using: db.docx.getIndexes()

  • Create Index

db.docx.createIndex({"name": 2}) // single field index
db.docx.createIndex({"name": 2, "date": 2}) // compound index
db.docx.createIndex({foo: "text", bar: "text"}) // text index
db.docx.createIndex({"$**": "text"}) // wildcard text index
db.docx.createIndex({"userMetadata.$**": 1}) // wildcard index


  • Drop Index: db.docx.dropIndex("name_3")


  • Hide/Unhide Indexes
    • To Hide: db.docx.hideIndex("name_3")


  • To Unhide: db.docx.unhideIndex("name_3")


  • Creating a compound index: db.docx.ensureIndex({name : 3, operator : 1, class : 0})


  • Dropping a compound index: db.docx.dropIndex({name : 3, operator : 1, class : 0})


5.

Update Row

Answer»

The MongoDB shell provides the following method to update row:

db.docx.update({ title: 'Post three' },
{
title: 'Post three,
body: 'New body for post 3',
date: Date()
},
{
upsert: true
})
6.

Update Multiple Document

Answer»

To update multiple document, use:

db.docx.update({"category": "Information"}, {$set: {"category": 'Sports'}})


7.

Update one document

Answer»

A document stored in the database can be changed using one of several update methods: updateOne, updateMany, and replaceOne. 

updateOne and updateMany take a filter document as their first parameter and a modifier document, which describes changes to make, as the second parameter. 

Command: db.docx.updateOne({"_id": 2}, {$set: {"title": 'revised title'}})


8.

Limit rows

Answer»

To limit the number of rows, use:

db.docx.find().limit(5).pretty()


9.

Count Rows

Answer»

To count number of rows, use:

db.docx.find().count()


10.

Sort rows

Answer»

The MongoDB shell provides the following methods to sort rows:

# asc
db.docx.find().sort({ title: 5 }).pretty() # desc
db.docx.find().sort({ title: -5}).pretty()
11.

Delete row

Answer»

To delete a row, use: 

db.docx.remove({ title: 'Post six' })


12.

Delete a document

Answer»

deleteOne and deleteMany can be used for this purpose. Both of these methods take a filter document as their first parameter.

db.docx.deleteOne({"_id" : 6})


13.

Find one row

Answer»

To find a row, use- 

db.docx.findOne({ category: 'Science' })


14.

Finding Documents using Operators

Answer»

The MongoDB shell provides the following methods to find documents using operators:

OperatorDescriptionCommands
$gt greater than db.docx.find({class:{$gt:'T'}
$gte greater than equalsdb.docx.find({class:{$gt:'T'}
$lt lesser than db.docx.find({class:{$lt:'T'}
$ltelesser than equalsdb.docx.find({class:{$lte:'T'}
$existsdoes an attribute exist or notdb.docx.find({class:{$gt:'T'}
$regexMatching pattern in pearl-styledb.docx.find({name:{$regex:'^USS\\sE'}})
$type search by type of an elementdb.docx.find({name : {$type:4}})

15.

Finding document

Answer»

The MongoDB shell provides the following methods to find documents:

S. No.CommandsDescription

1.

db.docx.findOne()Finds one random document.

2.

db.docx.find().prettyPrint()Finds all documents.

3.

db.docx.find({}, {name:true, _id:false})Displays only the names of the document Docx.

4.

db.docx.find({}, {name:true, _id:false})Can find one document by attribute among many documents.

16.

Insert Multiple Row

Answer»

The MongoDB shell provides the following methods to insert multiple rows:

db.docx.insertMany([
{
title: 'Post six,
body: 'Body of post six,
category: 'Science',
date: Date()
},
{
title: 'Post seven',
body: 'Body of post seven',
category: 'Information',
date: Date()
},
{
title: 'Post eight',
body: 'Body of post eight',
category: 'Sports',
date: Date()
}
])
17.

Insert Row

Answer»

The MongoDB shell provides the following methods to insert rows:

db.docx.insert({
title: 'Post Five',
body: 'Body of post five,
category: 'Information',
tags: ['Information', 'events'],
user: {
name: 'David',
status: 'author'
},
date: Date()
})
18.

Inserting Document

Answer»

The MongoDB shell provides the following methods to insert documents into a collection:

db.docx.insert({name:'Enterprise',operator:'Star',type:'Explorer',class:'Universe',crew:730,codes:[15,16,17]})
db.docx.insert({name:'Prometheus',operator:'Star',class:'Prometheus',crew:40,codes:[10,14,17]})
19.

Drop a database

Answer»

db.dropDatabase()


20.

Switch or create database

Answer»

 use acme


21.

To show current database

Answer»

db


22.

To show all databases

Answer»

show dbs


Previous Next