MongoDB Interview Q&A

Posted on

Q. What are NoSQL databases? What are the different types of NoSQL databases?

NoSQL is a non-relational DBMS, that does not require a fixed schema, avoids joins, and is easy to scale. The purpose of using a NoSQL database is for distributed data stores with humongous data storage needs. NoSQL is used for Big data and real-time web apps.

Types of NoSQL Databases

  • Document databases
  • Key-value stores
  • Column-oriented databases
  • Graph databases

1. Document databases

A document database stores data in JSON, BSON , or XML documents. In a document database, documents can be nested. Particular elements can be indexed for faster querying.

Documents can be stored and retrieved in a form that is much closer to the data objects used in applications, which means less translation is required to use the data in an application. SQL data must often be assembled and disassembled when moving back and forth between applications and storage.

Example: Amazon SimpleDB, CouchDB, MongoDB, Riak, Lotus Notes are popular Document originated DBMS systems.

Document Databases

2. Key-value Stores

Data is stored in key/value pairs. It is designed in such a way to handle lots of data and heavy load. Key-value pair storage databases store data as a hash table where each key is unique, and the value can be a JSON, BLOB(Binary Large Objects), string, etc.

Example: of key-value stores are Redis, Voldemort, Riak, and Amazon’s DynamoDB.

Key-value Stores

3. Column-Oriented Databases

Column-oriented databases work on columns and are based on BigTable paper by Google. Every column is treated separately. The values of single column databases are stored contiguously.

They deliver high performance on aggregation queries like SUM, COUNT, AVG, MIN, etc. as the data is readily available in a column.

Example: Column-based NoSQL databases are widely used to manage data warehouses, business intelligence, CRM, Library card catalogs, HBase, Cassandra, HBase, Hypertable are examples of a column-based database.

Column-Oriented Databases

4. Graph Databases

A graph type database stores entities as well the relations amongst those entities. The entity is stored as a node with the relationship as edges. An edge gives a relationship between nodes. Every node and edge has a unique identifier.

Compared to a relational database where tables are loosely connected, a Graph database is a multi-relational in nature. Traversing relationships as fast as they are already captured into the DB, and there is no need to calculate them.

Graph base databases mostly used for social networks, logistics, spatial data.

Example: Neo4J, Infinite Graph, OrientDB, FlockDB are some popular graph-based databases.

Graph Databases

Q. What is MongoDB?

MongoDB is a document-oriented NoSQL database used for high volume data storage. Instead of using tables and rows as in the traditional relational databases, MongoDB makes use of collections and documents. Documents consist of key-value pairs which are the basic unit of data in MongoDB. Collections contain sets of documents and function which is the equivalent of relational database tables.

Key Components

1. _id: The _id field represents a unique value in the MongoDB document. The _id field is like the document’s primary key. If you create a new document without an _id field, MongoDB will automatically create the field.

2. Collection: This is a grouping of MongoDB documents. A collection is the equivalent of a table which is created in any other RDMS such as Oracle.

3. Cursor: This is a pointer to the result set of a query. Clients can iterate through a cursor to retrieve results.

4. Database: This is a container for collections like in RDMS wherein it is a container for tables. Each database gets its own set of files on the file system. A MongoDB server can store multiple databases.

5. Document: A record in a MongoDB collection is basically called a document. The document, in turn, will consist of field name and values.

6. Field: A name-value pair in a document. A document has zero or more fields. Fields are analogous to columns in relational databases.

Example:

Connecting MongoDB Cloud using MongoDB Compass

MongoDB Compass

Q. What are Indexes in MongoDB?

Indexes support the efficient execution of queries in MongoDB. Without indexes, MongoDB must perform a collection scan, i.e. scan every document in a collection, to select those documents that match the query statement. If an appropriate index exists for a query, MongoDB can use the index to limit the number of documents it must inspect.

Indexes are special data structures that store a small portion of the collection’s data set in an easy to traverse form. The index stores the value of a specific field or set of fields, ordered by the value of the field. The ordering of the index entries supports efficient equality matches and range-based query operations. In addition, MongoDB can return sorted results by using the ordering in the index.

Example

The createIndex() method only creates an index if an index of the same specification does not already exist. The following example ( using Node.js ) creates a single key descending index on the name field:

collection.createIndex( { name : -1 }, function(err, result) {
   console.log(result);
   callback(result);
}

Q. What are the types of Indexes available in MongoDB?

MongoDB supports the following types of the index for running a query.

1. Single Field Index

MongoDB supports user-defined indexes like single field index. A single field index is used to create an index on the single field of a document. With single field index, MongoDB can traverse in ascending and descending order. By default, each collection has a single field index automatically created on the _id field, the primary key.

Example

{
  "_id": 1,
  "person": { name: "Alex", surname: "K" },
  "age": 29,
  "city": "New York"
}

We can define, a single field index on the age field.

db.people.createIndex( {age : 1} ) // creates an ascending index
 
db.people.createIndex( {age : -1} ) // creates a descending index

With this kind of index we can improve all the queries that find documents with a condition and the age field, like the following:

db.people.find( { age : 20 } )
db.people.find( { name : "Alex", age : 30 } )
db.people.find( { age : { $gt : 25} } )

2. Compound Index

A compound index is an index on multiple fields. Using the same people collection we can create a compound index combining the city and age field.

db.people.createIndex( {city: 1, age: 1, person.surname: 1  } )

In this case, we have created a compound index where the first entry is the value of the city field, the second is the value of the age field, and the third is the person.name. All the fields here are defined in ascending order.

Queries such as the following can benefit from the index:

db.people.find( { city: "Miami", age: { $gt: 50 } } )
db.people.find( { city: "Boston" } )
db.people.find( { city: "Atlanta", age: {$lt: 25}, "person.surname": "Green" } )

3. Multikey Index

This is the index type for arrays. When creating an index on an array, MongoDB will create an index entry for every element.

Example

{
   "_id": 1,
   "person": { name: "John", surname: "Brown" },
   "age": 34,
   "city": "New York",
   "hobbies": [ "music", "gardening", "skiing" ]
 }

The multikey index can be created as:

db.people.createIndex( { hobbies: 1} )

Queries such as these next examples will use the index:

db.people.find( { hobbies: "music" } )
db.people.find( { hobbies: "music", hobbies: "gardening" } )

4. Geospatial Index

GeoIndexes are a special index type that allows a search based on location, distance from a point and many other different features. To query geospatial data, MongoDB supports two types of indexes – 2d indexes and 2d sphere indexes. 2d indexes use planar geometry when returning results and 2dsphere indexes use spherical geometry to return results.

5. Text Index

It is another type of index that is supported by MongoDB. Text index supports searching for string content in a collection. These index types do not store language-specific stop words (e.g. “the”, “a”, “or”). Text indexes restrict the words in a collection to only store root words.

Example

Let’s insert some sample documents.

var entries = db.people("blogs").entries;
entries.insert( {
  title : "my blog post",
  text : "i am writing a blog. yay",
  site: "home",
  language: "english" });
entries.insert( {
  title : "my 2nd post",
  text : "this is a new blog i am typing. yay",
  site: "work",
  language: "english" });
entries.insert( {
  title : "knives are Fun",
  text : "this is a new blog i am writing. yay",
  site: "home",
  language: "english" });

Let’s define create the text index.

var entries = db.people("blogs").entries;
entries.ensureIndex({title: "text", text: "text"}, { weights: {
    title: 10,
    text: 5
  },
  name: "TextIndex",
  default_language: "english",
  language_override: "language" });

Queries such as these next examples will use the index:

var entries = db.people("blogs").entries;
entries.find({$text: {$search: "blog"}, site: "home"})

6. Hashed Index

MongoDB supports hash-based sharding and provides hashed indexes. These indexes are the hashes of the field value. Shards use hashed indexes and create a hash according to the field value to spread the writes across the sharded instances.

Q. Explain Index Properties in MongoDB?

1. TTL Indexes

TTL ( Time To Live ) is a special option that we can apply only to a single field index to permit the automatic deletion of documents after a certain time.

During index creation, we can define an expiration time. After that time, all the documents that are older than the expiration time will be removed from the collection. This kind of feature is very useful when we are dealing with data that don’t need to persist in the database ( eg. session data ).

Example

db.sessionlog.createIndex( { "lastUpdateTime": 1 }, { expireAfterSeconds: 1800 } )

In this case, MongoDB will drop the documents from the collection automatically once half an hour (1800 seconds) has passed since the value in lastUpdateTime field.

Restrictions

  • Only single field indexes can have the TTL option
  • the _id single field index cannot support the TTL option
  • the indexed field must be a date type
  • a capped collection cannot have a TTL index

2. Partial indexes

A partial index is an index that contains only a subset of the values based on a filter rule. They are useful in cases where:

  • The index size can be reduced
  • We want to index the most relevant and used values in the query conditions
  • We want to index the most selective values of a field

Example

db.people.createIndex(
   { "city": 1, "person.surname": 1 },
   { partialFilterExpression: { age : { $lt: 30 } } }
)

We have created a compound index on city and person.surname but only for the documents with age less than 30. In order for the partial index to be used the queries must contain a condition on the age field.

db.people.find( { city: "New Tork", age: { $eq: 20} } )

3. Sparse indexes

Sparse indexes are a subset of partial indexes. A sparse index only contains elements for the documents that have the indexed field, even if it is null.

Since MongoDB is a schemaless database, the documents in a collection can have different fields, so an indexed field may not be present in some of them.

Example

To create such an index use the sparse option:

db.people.createIndex( { city: 1 }, { sparse: true } )

In this case, we are assuming there could be documents in the collection with the field city missing. Sparse indexes are based on the existence of a field in the documents and are useful to reduce the size of the index.

4. Unique indexes

MongoDB can create an index as unique. An index defined this way cannot contain duplicate entries.

Example

db.people.createIndex( { city: 1 }, { unique: true } )

Uniqueness can be defined for compound indexes too.

db.people.createIndex( { city: 1, person.surname: 1}, { unique: true } )

By default, the index on _id is automatically created as unique.

Q. How many indexes does MongoDB create by default for a new collection?

By default MongoDB creates a unique index on the _id field during the creation of a collection. The _id index prevents clients from inserting two documents with the same value for the _id field.

Q. Can you create an index on an array field in MongoDB?

Yes. An array field can be indexed in MongoDB. In this case, MongoDB would index each value of the array.

Q. Why does Profiler use in MongoDB?

The database profiler captures data information about read and write operations, cursor operations, and database commands. The database profiler writes data in the system.profile collection, which is a capped collection.

The database profiler collects detailed information about Database Commands executed against a running mongod instance. This includes CRUD operations as well as configuration and administration commands.

Profiler has 3 profiling levels.

  • Level 0 – Profiler will not log any data
  • Level 1 – Profiler will log only slow operations above some threshold
  • Level 2 – Profiler will log all the operations

1. To get current profiling level.

db.getProfilingLevel()  
 
// Output
0

2. To check current profiling status

db.getProfilingStatus()
 
 
// Output
{ "was" : 0, "slowms" : 100 }

3. To set profiling level

db.setProfilingLevel(1, 40)
 
// Output
{ "was" : 0, "slowms" : 100, "ok" : 1 }

Q. How to remove attribute from MongoDB Object?

$unset

The $unset operator deletes a particular field. If the field does not exist, then $unset does nothing. When used with $ to match an array element, $unset replaces the matching element with null rather than removing the matching element from the array. This behavior keeps consistent the array size and element positions.

syntax:

{ $unset: { <field1>: "", ... } }

Example:

delete the properties.service attribute from all records on this collection.

db.collection.update(
    {},
    {
        $unset : {
            "properties.service" : 1
        }
    },
    {
        multi: true
    }
);

To verify they have been deleted you can use:

db.collection.find(
    {
        "properties.service" : {
            $exists : true
         }
    }
).count(true);

Q. What is “Namespace” in MongoDB?

MongoDB stores BSON (Binary Interchange and Structure Object Notation) objects in the collection. The concatenation of the collection name and database name is called a namespace

Q. Mention the command to insert a document in a database called school and collection called persons?

use school;
db.persons.insert( { name: "Alex", age: "28" } )

Q. What is Replication in Mongodb?

Replication exists primarily to offer data redundancy and high availability. It maintain the durability of data by keeping multiple copies or replicas of that data on physically isolated servers. Replication allows to increase data availability by creating multiple copies of data across servers. This is especially useful if a server crashes or hardware failure.

With MongoDB, replication is achieved through a Replica Set. Writer operations are sent to the primary server (node), which applies the operations across secondary servers, replicating the data. If the primary server fails (through a crash or system failure), one of the secondary servers takes over and becomes the new primary node via election. If that server comes back online, it becomes a secondary once it fully recovers, aiding the new primary node.

Q. What is Replica Set in MongoDB?

It is a group of mongo processes that maintain same data set. Replica sets provide redundancy and high availability, and are the basis for all production deployments. A replica set contains a primary node and multiple secondary nodes.

The primary node receives all write operations. A replica set can have only one primary capable of confirming writes with { w: "majority" } write concern; although in some circumstances, another mongod instance may transiently believe itself to also be primary.

The secondaries replicate the primary’s oplog and apply the operations to their data sets such that the secondaries’ data sets reflect the primary’s data set. If the primary is unavailable, an eligible secondary will hold an election to elect itself the new primary.

Replica Set

Q. How does MongoDB ensure high availability?

High Availability (HA) refers to the improvement of system and app availability by minimizing the downtime caused by routine maintenance operations (planned) and sudden system crashes (unplanned).

Replica Set

The replica set mechanism of MongoDB has two main purposes:

  • One is for data redundancy for failure recovery. When the hardware fails, or the node is down for other reasons, you can use a replica for recovery.
  • The other purpose is for read-write splitting. It routes the reading requests to the replica to reduce the reading pressure on the primary node.

MongoDB automatically maintains replica sets, multiple copies of data that are distributed across servers, racks and data centers. Replica sets help prevent database downtime using native replication and automatic failover.

A replica set consists of multiple replica set members. At any given time, one member acts as the primary member, and the other members act as secondary members. If the primary member fails for any reason (e.g., hardware failure), one of the secondary members is automatically elected to primary and begins to process all reads and writes.

Q. What is an Embedded MongoDB Document?

An embedded, or nested, MongoDB Document is a normal document that is nested inside another document within a MongoDB collection. Embedding connected data in a single document can reduce the number of read operations required to obtain data. In general, we should structure our schema so that application receives all of its required information in a single read operation.

Example:

In the normalized data model, the address documents contain a reference to the patron document.

// patron document
{
   _id: "joe",
   name: "Joe Bookreader"
}
 
// address documents
{
   patron_id: "joe", // reference to patron document
   street: "123 Fake Street",
   city: "Faketon",
   state: "MA",
   zip: "12345"
}
 
{
   patron_id: "joe",
   street: "1 Some Other Street",
   city: "Boston",
   state: "MA",
   zip: "12345"
}

Embedded documents are particularly useful when a one-to-many relationship exists between documents. In the example shown above, we see that a single customer has multiple addresses associated with him. The nested document structure makes it easy to retrieve complete address information about this customer with just a single query.

Q. How can you achieve primary key – foreign key relationships in MongoDB?

The primary key-foreign key relationship can be achieved by embedding one document inside the another. As an example, a department document can have its employee document(s).

Q. When should we embed one document within another in MongoDB?

You should consider embedding documents for:

  • contains relationships between entities
  • One-to-many relationships
  • Performance reasons

Q. How is data stored in MongoDB?

In MongoDB, Data is stored in BSON documents (short for Bin­ary JSON). These documents are stored in MongoDB in JSON (JavaScript Object Notation) format. JSON documents support embedded fields, so related data and lists of data can be stored with the document instead of an external table. Documents contain one or more fields, and each field contains a value of a specific data type, including arrays, binary data and sub-documents. Documents that tend to share a similar structure are organized as collections.

JSON is formatted as name/value pairs. In JSON documents, field names and values are separated by a colon, field name and value pairs are separated by commas, and sets of fields are encapsulated in “curly braces” ({}).

Example:

{
  "name": "notebook",
  "qty": 50,
  "rating": [ { "score": 8 }, { "score": 9 } ],
  "size": { "height": 11, "width": 8.5, "unit": "in" },
  "status": "A",
  "tags": [ "college-ruled", "perforated"]
}

Q. What are the differences between MongoDB and SQL-SERVER?

  • The MongoDB store the data in documents with JSON format but SQL store the data in Table format.
  • The MongoDB provides high performance, high availability, easy scalability etc. rather than SQL Server.
  • In the MongoDB, we can change the structure simply by adding, removing column from the existing documents.

MongoDB and SQL Server Comparision Table

Base of ComparisonMS SQL ServerMongoDB
Storage ModelRDBMSDocument-Oriented
JoinsYesNo
TransactionACIDMulti-document ACID Transactions with snapshot isolation
Agile practicesNoYes
Data SchemaFixedDynamic
ScalabilityVerticalHorizontal
Map ReduceNoYes
LanguageSQL query languageJSON Query Language
Secondary indexYesYes
TriggersYesYes
Foreign KeysYesNo
ConcurrencyYesyes
XML SupportYesNo
MongoDB & SQL Server

Q. How can you achieve transaction and locking in MongoDB?

In MongoDB (4.2), an operation on a single document is atomic. For situations that require atomicity of reads and writes to multiple documents (in a single or multiple collections), MongoDB supports multi-document transactions. With distributed transactions, transactions can be used across multiple operations, collections, databases, documents, and shards.

MongoDB allows multiple clients to read and write the same data. In order to ensure consistency, it uses locking and other concurrency control measures to prevent multiple clients from modifying the same piece of data simultaneously.

MongoDB uses multi-granularity locking that allows operations to lock at the global, database or collection level, and allows for individual storage engines to implement their own concurrency control below the collection level (e.g., at the document-level in WiredTiger). MongoDB uses reader-writer locks that allow concurrent readers shared access to a resource, such as a database or collection.

The lock modes are represented as follows:

Lock ModeDescription
RRepresents Shared (S) lock.
WRepresents Exclusive (X) lock.
rRepresents Intent Shared (IS) lock.
wRepresents Intent Exclusive (IX) lock.

Example:

The following example highlights the key components of the transactions API

const client = new MongoClient(uri);
await client.connect();
 
// Prereq: Create collections.
 
await client.db('mydb1').collection('foo').insertOne({ abc: 0 }, { w: 'majority' });
 
await client.db('mydb2').collection('bar').insertOne({ xyz: 0 }, { w: 'majority' });
 
// Step 1: Start a Client Session
const session = client.startSession();
 
// Step 2: Optional. Define options to use for the transaction
const transactionOptions = {
  readPreference: 'primary',
  readConcern: { level: 'local' },
  writeConcern: { w: 'majority' }
};
 
// Step 3: Use withTransaction to start a transaction, execute the callback, and commit (or abort on error)
// Note: The callback for withTransaction MUST be async and/or return a Promise.
try {
  await session.withTransaction(async () => {
    const coll1 = client.db('mydb1').collection('foo');
    const coll2 = client.db('mydb2').collection('bar');
 
    // Important:: You must pass the session to the operations
 
    await coll1.insertOne({ abc: 1 }, { session });
    await coll2.insertOne({ xyz: 999 }, { session });
  }, transactionOptions);
} finally {
   await session.endSession();
   await client.close();
}

Q. When to Use MongoDB Rather than MySQL?

1. MongoDB

MongoDB is one of the most popular document-oriented databases under the banner of NoSQL database. It employs the format of key-value pairs, here called document store. Document stores in MongoDB are created is stored in BSON files which are, in fact, a little-modified version of JSON files and hence all JS are supported.

It offers greater efficiency and reliability which in turn can meet your storage capacity and speed demands. The schema-free implementation of MongoDB eliminates the prerequisites of defining a fixed structure. These models allow hierarchical relationships representation and facilitate the ability to change the structure of the record.

Pros

  • MongoDB has a lower latency per query & spends less CPU time per query because it is doing a lot less work (e.g. no joins, transactions). As a result, it can handle a higher load in terms of queries per second.
  • MongoDB is easier to shard (use in a cluster) because it doesn’t have to worry about transactions and consistency.
  • MongoDB has a faster write speed because it does not have to worry about transactions or rollbacks (and thus does not have to worry about locking).
  • It supports many Features like automatic repair, easier data distribution, and simpler data models make administration and tuning requirements lesser in NoSQL.
  • NoSQL databases are cheap and open source.
  • NoSQL database support caching in system memory so it increases data output performance.

Cons

  • MongoDB does not support transactions.
  • In general, MongoDB creates more work (e.g. more CPU cost) for the client server. For example, to join data one has to issue multiple queries and do the join on the client.
  • No Stored Procedures in mongo dB (NoSQL database).

Reasons to Use a NoSQL Database

  • Storing large volumes of data without structure: A NoSQL database doesn’t limit storable data types. Plus, you can add new types as business needs change.
  • Using cloud computing and storage: Cloud-based storage is a great solution, but it requires data to be easily spread across multiple servers for scaling. Using affordable hardware on-site for testing and then for production in the cloud is what NoSQL databases are designed for.
  • Rapid development: If you are developing using modern agile methodologies, a relational database will slow you down. A NoSQL database doesn’t require the level of preparation typically needed for relational databases.

2. MySQL

MySQL is a popular open-source relational database management system (RDBMS) that is developed, distributed and supported by Oracle Corporation. MySQL stores data in tables and uses structured query language (SQL) for database access. It uses Structured Query Language SQL to access and transfer the data and commands such as ‘SELECT’, ‘UPDATE’, ‘INSERT’ and ‘DELETE’ to manage it.

Related information is stored in different tables but the concept of JOIN operations simplifies the process of correlating it and performing queries across multiple tables and minimize the chances of data duplication. It follows the ACID (Atomic, Consistent, Isolated and Durable) model. This means that once a transaction is complete, the data remains consistent and stable on the disc which may include distinct multiple memory locations.

Pros

  • SQL databases are table based databases.
  • Data store in rows and columns
  • Each row contains a unique instance of data for the categories defined by the columns.
  • Provide facility primary key, to uniquely identify the rows.

Cons

  • Users have to scale relational database on powerful servers that are expensive and difficult to handle. To scale relational database, it has to be distributed on to multiple servers. Handling tables across different servers is difficult.
  • In SQL server’s data has to fit into tables anyhow. If your data doesn’t fit into tables, then you need to design your database structure that will be complex and again difficult to handle.

Q. How MongoDB supports ACID transactions and locking functionalities?

MongoDB, has always supported ACID transactions in a single document and, when leveraging the document model appropriately, many applications don’t need ACID guarantees across multiple documents.

MongoDB is a document based NoSQL database with a flexible schema. Transactions are not operations that should be executed for every write operation since they incur a greater performance cost over a single document writes. With a document based structure and denormalized data model, there will be a minimized need for transactions. Since MongoDB allows document embedding, you don’t necessarily need to use a transaction to meet a write operation.

MongoDB version 4.0 provides multi-document transaction support for replica set deployments only and probably the version 4.2 will extend support for sharded deployments.

Example: Multi-Document ACID Transactions in MongoDB

These are multi-statement operations that need to be executed sequentially without affecting each other. For example below we can create two transactions, one to add a user and another to update a user with a field of age.

$session.startTransaction()
 
   db.users.insert({_id:6, name “Ibrahim”})
 
   db.users.updateOne({_id:3 , {$set:{age:50}}})
 
session.commit_transaction()

Transactions can be applied to operations against multiple documents contained in one or many collection/database. Any changes due to document transaction do not impact performance for workloads not related or do not require them. Until the transaction is committed, uncommitted writes are neither replicated to the secondary nodes nor are they readable outside the transactions.

Q. What are the best practices for MongoDB Transactions?

The multi-document transactions are only supported in the WiredTiger storage engine. For a single ACID transaction, if you try performing an excessive number of operations, it can result in high pressure on the WiredTiger cache. The cache is always dictated to maintain state for all subsequent writes since the oldest snapshot was created. This means new writes will accumulate in the cache throughout the duration of the transaction and will be flushed only after transactions currently running on old snapshots are committed or aborted.

For the best database performance on the transaction, developers should consider:

  1. Always modify a small number of documents in a transaction. Otherwise, you will need to break the transaction into different parts and process the documents in different batches. At most, process 1000 documents at a time.
  2. Temporary exceptions such as awaiting to elect primary and transient network hiccups may result in abortion of the transaction. Developers should establish a logic to retry the transaction if the defined errors are presented.
  3. Configure optimal duration for the execution of the transaction from the default 60 seconds provided by MongoDB. Besides, employ indexing so that it can allow fast data access within the transaction.
  4. Decompose your transaction into a small set of operation so that it fits the 16MB size constraints. Otherwise, if the operation together with oplog description exceed this limit, the transaction will be aborted.
  5. All data relating to an entity should be stored in a single, rich document structure. This is to reduce the number of documents that are to be cached when different fields are going to be changed.

Q. Explain limitations of MongoDB Transactions?

MongoDB transactions can exist only for relatively short time periods. By default, a transaction must span no more than one minute of clock time. This limitation results from the underlying MongoDB implementation. MongoDB uses MVCC, but unlike databases such as Oracle, the “older” versions of data are kept only in memory.

  1. You cannot create or drop a collection inside a transaction.
  2. Transactions cannot make writes to a capped collection
  3. Transactions take plenty of time to execute and somehow they can slow the performance of the database.
  4. Transaction size is limited to 16MB requiring one to split any that tends to exceed this size into smaller transactions.
  5. Subjecting a large number of documents to a transaction may exert excessive pressure on the WiredTiger engine and since it relies on the snapshot capability, there will be a retention of large unflushed operations in memory. This renders some performance cost on the database.

Q. How to combine data from multiple collections into one collection?

$lookup

Performs a left outer join to an unsharded collection in the same database to filter in documents from the “joined” collection for processing. To each input document, the $lookup stage adds a new array field whose elements are the matching documents from the “joined” collection. The $lookup stage passes these reshaped documents to the next stage.

Syntax

{
   $lookup:
     {
       from: <collection to join>,
       localField: <field from the input documents>,
       foreignField: <field from the documents of the "from" collection>,
       as: <output array field>
     }
}

Q. Find objects between two dates MongoDB?

Operator $gte and $lt is used to find objects between two dates in MongoDB.

Example: Creating a collection

>db.order.insert({"OrderId":1,"OrderAddrees":"US","OrderDateTime":ISODate("2020-02-19")};
WriteResult({ "nInserted" : 1 })
 
>db.order.insert({"OrderId":2,"OrderAddrees":"UK","OrderDateTime":ISODate("2020-02-26")};
WriteResult({ "nInserted" : 1 })

Display all documents from the collection using find() method.

> db.order.find().pretty();
 
// Output
{
   "_id" : ObjectId("5c6c072068174aae23f5ef57"),
   "OrderId" : 1,
   "OrderAddrees" : "US",
   "OrderDateTime" : ISODate("2020-02-19T00:00:00Z")
}
{
   "_id" : ObjectId("5c6c073568174aae23f5ef58"),
   "OrderId" : 2,
   "OrderAddrees" : "UK",
   "OrderDateTime" : ISODate("2020-02-26T00:00:00Z")
}

Here is the query to find objects between two dates:

> db.order.find({"OrderDateTime":{ $gte:ISODate("2020-02-10"), $lt:ISODate("2020-02-21") }
}).pretty();
 
 
// Output
{
   "_id" : ObjectId("5c6c072068174aae23f5ef57"),
   "OrderId" : 1,
   "OrderAddrees" : "US",
   "OrderDateTime" : ISODate("2020-02-19T00:00:00Z")
}

Q. How to query MongoDB with “like”?

db.users.insert({name: 'paulo'})
db.users.insert({name: 'patric'})
db.users.insert({name: 'pedro'})
 
db.users.find({name: /a/})  //like '%a%'
db.users.find({name: /^pa/}) //like 'pa%'
db.users.find({name: /ro$/}) //like '%ro'

Q. Should I normalize my data before storing it in MongoDB?

Data used by multiple documents can either be embedded (denormalized) or referenced (normalized). Normalization, which is increasing the complexity of the schema by splitting tables into multiple smaller ones to reduce the data redundancy( 1NF, 2NF, 3NF).

But Mongo follows the exact opposite way of what we do with SQL. In MongoDB, data normalization is not requried. Indeed we need to de-normalize and fit it into a collection of multiple documents.

Example: Let’s say we have three tables

  • Table – 1 : ColumnA, ColumnB (primary key)
  • Table – 2 : ColumnC (Foreign key), ColumnD (primary key)
  • Table – 3 : ColumnE (foreign key), ColumnF

In this case, mongoDB document structure should be as follows.

{
    ColumnA : ValueA,
    ColumnB : ValueB,
    Subset1 : [{
       ColumnC : ValueC,
       ColumnD : ValueD,
       Subset2 : [{
           ColumnE : ValueE,
           ColumnF : ValueF
       }]
    }]
}

Q. What is upsert operation in MongoDB?

Upsert operation in MongoDB is utilized to save document into collection. If document matches query criteria then it will perform update operation otherwise it will insert a new document into collection.

Upsert operation is useful while importing data from external source which will update existing documents if matched otherwise it will insert new documents into collection.

Example: Upsert option set for update

This operation first searches for the document if not present then inserts the new document into the database.

> db.car.update(
...    { name: "Qualis" },
...    {
...       name: "Qualis",
...       speed: 50
...    },
...    { upsert: true }
... )
WriteResult({
        "nMatched" : 0,
        "nUpserted" : 1,
        "nModified" : 0,
        "_id" : ObjectId("548d3a955a5072e76925dc1c")
})

The car with the name Qualis is checked for existence and if not, a document with car name “Qualis” and speed 50 is inserted into the database. The nUpserted with value “1” indicates a new document is inserted.

Q. Is there an “upsert” option in the mongodb insert command?

The db.collection.insert() provides no upsert possibility. Instead, mongo insert inserts a new document into a collection. Upsert is only possible using db.collection.update() and db.collection.save().

Q. What is oplog?

The OpLog (Operations Log) is a special capped collection that keeps a rolling record of all operations that modify the data stored in databases.

MongoDB applies database operations on the primary and then records the operations on the primary’s oplog. The secondary members then copy and apply these operations in an asynchronous process. All replica set members contain a copy of the oplog, in the local.oplog.rs collection, which allows them to maintain the current state of the database.

Each operation in the oplog is idempotent. That is, oplog operations produce the same results whether applied once or multiple times to the target dataset.

Example: Querying The OpLog

MongoDB shell version: 2.0.4
connecting to: mongodb:27017/test
PRIMARY> use local
PRIMARY> db.oplog.rs.find()

Q. Does MongoDB pushes the writes to disk immediately or lazily?

MongoDB pushes the data to disk lazily. It updates the immediately written to the journal but writing the data from journal to disk happens lazily.

Q. How to perform a delete operation in MongoDB?

MongoDB’s db.collection.deleteMany() and db.collection.deleteOne() method is used to delete documents from the collection. Delete operations do not drop indexes, even if deleting all documents from a collection. All write operations in MongoDB are atomic on the level of a single document.

Example:

// Create Inventory Collection
db.inventory.insertMany( [
   { item: "journal", qty: 25, size: { h: 14, w: 21, uom: "cm" }, status: "A" },
   { item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in" }, status: "P" },
   { item: "paper", qty: 100, size: { h: 8.5, w: 11, uom: "in" }, status: "D" },
   { item: "planner", qty: 75, size: { h: 22.85, w: 30, uom: "cm" }, status: "D" },
   { item: "postcard", qty: 45, size: { h: 10, w: 15.25, uom: "cm" }, status: "A" },
] );
 
 
 
// Delete Commands
db.inventory.deleteMany({}) // Delete All Documents
 
db.inventory.deleteMany({ status : "A" }) // Delete All Documents that Match a Condition
 
db.inventory.deleteOne( { status: "D" } ) // Delete Only One Document that Matches a Condition

Q. If you remove a document from database, does MongoDB remove it from disk?

Yes. If you remove a document from database, MongoDB will remove it from disk too.

Q. Explain the structure of ObjectID in MongoDB?

The ObjectId(<hexadecimal>) class is the default primary key for a MongoDB document and is usually found in the _id field in an inserted document. It returns a new ObjectId value. The 12-byte ObjectId value consists of:

  • a 4-byte timestamp value, representing the ObjectId’s creation, measured in seconds since the Unix epoch
  • a 5-byte random value
  • a 3-byte incrementing counter, initialized to a random value
Document Databases

While the BSON format itself is little-endian, the timestamp and counter values are big-endian, with the most significant bytes appearing first in the byte sequence.

Create ObjectId

To create a new objectID manually within the MongoDB we can declare objectId() as a method.

> newObjectId = ObjectId();
 
// Output
ObjectId("5349b4ddd2781d08c09890f3")

MongoDB provides three methods for ObjectId

MethodDescription
ObjectId.getTimestamp()Returns the timestamp portion of the object as a Date.
ObjectId.toString()Returns the JavaScript representation in the form of a string literal “ObjectId(…)”.
ObjectId.valueOf()Returns the representation of the object as a hexadecimal string.

Q. What is a covered query in MongoDB?

The MongoDB covered query is one which uses an index and does not have to examine any documents. An index will cover a query if it satisfies the following conditions:

  • All fields in a query are part of an index.
  • All fields returned in the results are of the same index.
  • no fields in the query are equal to null

Since all the fields present in the query are part of an index, MongoDB matches the query conditions and returns the result using the same index without actually looking inside the documents.

Example:

A collection inventory has the following index on the type and item fields:

db.inventory.createIndex( { type: 1, item: 1 } )

This index will cover the following operation which queries on the type and item fields and returns only the item field:

db.inventory.find(
   { type: "food", item:/^c/ },
   { item: 1, _id: 0 }
)

Q. Why MongoDB is not preferred over a 32-bit system?

When running a 32-bit system build of MongoDB, the total storage size for the server, including data and indexes, is 2 gigabytes. The reason for this is that the MongoDB storage engine uses memory-mapped files for performance.

Q. What is Sharding in MongoDB?

Sharding is a method for distributing data across multiple machines. MongoDB uses sharding to support deployments with very large data sets and high throughput operations.

Database systems with large data sets or high throughput applications can challenge the capacity of a single server. For example, high query rates can exhaust the CPU capacity of the server. Working set sizes larger than the system’s RAM stress the I/O capacity of disk drives. There are two methods for addressing system growth: vertical and horizontal scaling.

1. Vertical Scaling

Vertical Scaling involves increasing the capacity of a single server, such as using a more powerful CPU, adding more RAM, or increasing the amount of storage space.

2. Horizontal Scaling

Horizontal Scaling involves dividing the system dataset and load over multiple servers, adding additional servers to increase capacity as required. While the overall speed or capacity of a single machine may not be high, each machine handles a subset of the overall workload, potentially providing better efficiency than a single high-speed high-capacity server.

Document Databases

MongoDB supports horizontal scaling through sharding. A MongoDB sharded cluster consists of the following components:

  • Shards: Each shard contains a subset of the sharded data. Each shard can be deployed as a replica set.
  • Mongos: The mongos acts as a query router, providing an interface between client applications and the sharded cluster. Starting in MongoDB 4.4, mongos can support hedged reads to minimize latencies.
  • Config Servers: Config servers store metadata and configuration settings for the cluster.

Q. What is Aggregation in MongoDB?

Aggregation in MongoDB is an operation used to process the data that returns the computed results. Aggregation basically groups the data from multiple documents and operates in many ways on those grouped data in order to return one combined result.

Aggregate function groups the records in a collection, and can be used to provide total number(sum), average, minimum, maximum etc out of the group selected. In order to perform the aggregate function in MongoDB, aggregate () is the function to be used. Following is the syntax for aggregation

db.collection_name.aggregate(aggregate_operation)

MongoDB’s aggregation framework is modeled on the concept of data processing pipelines. Documents enter a multi-stage pipeline that transforms the documents into an aggregated result.

Example

db.orders.aggregate([
   { $match: { status: "A" } },
   { $group: { _id: "$cust_id", total: { $sum: "$amount" } } }
]);

The $match stage filters the documents by the status field and passes to the next stage those documents that have status equal to “A”. The $group stage groups the documents by the cust_id field to calculate the sum of the amount for each unique cust_id.

Expressions used by Aggregate function

ExpressionDescription
$sumSummates the defined values from all the documents in a collection
$avgCalculates the average values from all the documents in a collection
$minReturn the minimum of all values of documents in a collection
$maxReturn the maximum of all values of documents in a collection
$addToSetInserts values to an array but no duplicates in the resulting document
$pushInserts values to an array in the resulting document
$firstReturns the first document from the source document
$lastReturns the last document from the source document

Q. How can you isolate your cursors from intervening with the write operations?

As cursor is not isolated during its lifetime, thus intervening write operations on a document may result in cursor that returns a document more than once. The snapshot() method can be used on a cursor to isolate the operation for a very specific case. snapshot() traverses the index on the _id field and guarantees that the query will return each document no more than once.

Restriction:

  • We cannot use snapshot() with sharded collections.
  • We cannot use snapshot() with sort() or hint() cursor methods.

Q. At what interval does MongoDB write updates to the disk?

By default configuration, MongoDB writes updates to the disk every 60 seconds. However, this is configurable with the commitIntervalMs and syncPeriodSecs options.

Q. Mention the command to remove indexes and list all the indexes on a particular collection?

List all Indexes on a Collection

// To view all indexes on the people collection
 
db.people.getIndexes()

List all Indexes for a Database

// To list all the collection indexes in a database
 
db.getCollectionNames().forEach(function(collection) {
   indexes = db[collection].getIndexes();
   print("Indexes for " + collection + ":");
   printjson(indexes);
});

Remove Indexes

MongoDB provides two methods for removing indexes from a collection:

  • db.collection.dropIndex()
  • db.collection.dropIndexes()

1. Remove Specific Index

db.accounts.dropIndex( { "tax-id": 1 } )
 
 
// Output
{ "nIndexesWas" : 3, "ok" : 1 }

2. Remove All Indexes

// The following command removes all indexes from the accounts collection
 
db.accounts.dropIndexes()

Q. What happens if an index does not fit into RAM?

If the indexes does not fit into RAM, MongoDB reads data from disk which is relatively very much slower than reading from RAM.

Indexes do not have to fit entirely into RAM in all cases. If the value of the indexed field increments with every insert, and most queries select recently added documents; then MongoDB only needs to keep the parts of the index that hold the most recent or “right-most” values in RAM. This allows for efficient index use for read and write operations and minimize the amount of RAM required to support the index.

Example: To check the size of indexes

> db.collection.totalIndexSize()
 
// Output (in bytes)
4294976499 

MongoDB supports query operations that perform a text search of string content. To perform text search, MongoDB uses a text index and the $text operator.

Example

A collection stores with the following documents:

db.stores.insert(
   [
     { _id: 1, name: "Java Hut", description: "Coffee and cakes" },
     { _id: 2, name: "Burger Buns", description: "Gourmet hamburgers" },
     { _id: 3, name: "Coffee Shop", description: "Just coffee" },
     { _id: 4, name: "Clothes Clothes Clothes", description: "Discount clothing" },
     { _id: 5, name: "Java Shopping", description: "Indonesian goods" }
   ]
)

1. Text Index

MongoDB provides text indexes to support text search queries on string content. text indexes can include any field whose value is a string or an array of string elements.

db.stores.createIndex( { name: "text", description: "text" } )

2. $text Operator

Use the $text query operator to perform text searches on a collection with a text index. $text will tokenize the search string using whitespace and most punctuation as delimiters, and perform a logical OR of all such tokens in the search string.

Example:

// Returns all stores containing any terms from the list “coffee”, “shop”, and “java”
db.stores.find( { $text: { $search: "java coffee shop" } } )
 
 
// Returns all documents containing “coffee shop”
db.stores.find( { $text: { $search: "\"coffee shop\"" } } )
 
 
// Returns all stores containing “java” or “shop” but not “coffee”
db.stores.find( { $text: { $search: "java shop -coffee" } } )

Q. How does Journaling work in MongoDB?

Mongod primarily hosts the write operations in memory in shared view. It is called shared because it has memory mapping in actual disc. In this process, a write operation occurs in mongod, which then creates changes in private view. The first block is memory and the second block is “my disc”. After a specified interval, which is called a “journal commit interval”, the private view writes those operations in journal directory (residing in the disc).

Once the journal commit happens, mongod pushes data into shared view. As part of the process, it gets written to actual data directory from the shared view (as this process happens in background). The basic advantage is, we have a reduced cycle from 60 seconds to 200 milliseconds.

In a scenario where an abruption occurs at any point of time or flash disc remains unavailable for last 59 seconds , then when the next time mongod starts, it basically replays all write operation logs and writes into the actual data directory.

Document Databases

Q. Is MongoDB schema-less?

As a NoSQL database, MongoDB is considered schemaless because it does not require a rigid, pre-defined schema like a relational database. The database management system (DBMS) enforces a partial schema as data is written, explicitly listing collections and indexes.

MongoDB is a document based database, which does not use the concept of tables and columns, instead of which it uses the concept of documents and collections. All the referential data with respect to different modules will be stored as one collection. More over the BSON data structure used by MongoDB can easily have varying sets of data and fields with different types.

When we say schemaless, we actually mean dynamically typed schema, as opposed to statically typed schemas as available in RDBMS(SQL) databases. JSON is a completely schema free data structure, as opposed to XML which allows you to specify XSD if you need.

Q. What is a Storage Engine in MongoDB?

The storage engine is the component of the database that is responsible for managing how data is stored, both in memory and on disk. MongoDB supports multiple storage engines, as different engines perform better for specific workloads.

Example: command to find storage engine

> db.serverStatus().storageEngine
 
// Output
{
    "name" : "wiredTiger",
    "supportsCommittedReads" : true,
    "oldestRequiredTimestampForCrashRecovery" : Timestamp(0, 0),
    "supportsPendingDrops" : true,
    "dropPendingIdents" : NumberLong(0),
    "supportsTwoPhaseIndexBuild" : true,
    "supportsSnapshotReadConcern" : true,
    "readOnly" : false,
    "persistent" : true,
    "backupCursorOpen" : false
}
Storage Engine

MongoDB supports mainly 3 storage engines whose performance differ in accordance to some specific workloads. The storage engines are:

  • WiredTiger Storage Engine
  • In-Memory Storage Engine
  • MMAPv1 Storage Engine

1. WiredTiger Storage Engine

WiredTiger is the default storage engine starting in MongoDB 3.2. It is well-suited for most workloads and is recommended for new deployments. WiredTiger provides a document-level concurrency model, checkpointing, and compression, among other features. The WiredTiger storage engine has both configurations of a B-Tree Based Engine and a Log Structured Merge Tree Based Engine.

2. In-Memory Storage Engine

In-Memory Storage Engine is available in MongoDB Enterprise. Rather than storing documents on-disk, it retains them in-memory for more predictable data latencies.

3. MMAPv1 Storage Engine

MMAPv1 is a B-tree based system which powers many of the functions such as storage interaction and memory management to the operating system. Its name comes from the fact that it uses memory mapped files to access data. It does so by directly loading and modifying file contents, which are in a virtual memory through a mmap() syscall methodology.

Storage Engine

Q. How to condense large volumes of data in Mongodb?

compact

Rewrites and defragments all data and indexes in a collection. On WiredTiger databases, this command will release unneeded disk space to the operating system. This command will perform a compaction “in-line”.

MongoDB compresses the files by:

  • copying the files to a new location
  • looping through the documents and re-ordering / re-solving them
  • replacing the original files with the new files

Syntax

{ compact: <collection name> }

Q. Is it possible to update MongoDB field using value of another field?

The aggregate function can be used to update MongoDB field using the value of another field.

Example

db.collection.<update method>(
    {},
    [
        {"$set": {"name": { "$concat": ["$firstName", " ", "$lastName"]}}}
    ]
)

Q. How to check if a field contains a substring?

The $regex operator can be used to check if a field contains a string in MongoDB.

db.users.findOne({"username" : {$regex : ".*some_string.*"}});

Q. How to find document with array that contains a specific value?

Populate the inventory collection

db.inventory.insertMany([
   { item: "journal", qty: 25, tags: ["blank", "red"], dim_cm: [ 14, 21 ] },
   { item: "notebook", qty: 50, tags: ["red", "blank"], dim_cm: [ 14, 21 ] },
   { item: "paper", qty: 100, tags: ["red", "blank", "plain"], dim_cm: [ 14, 21 ] },
   { item: "planner", qty: 75, tags: ["blank", "red"], dim_cm: [ 22.85, 30 ] },
   { item: "postcard", qty: 45, tags: ["blue"], dim_cm: [ 10, 15.25 ] }
]);

To query if the array field contains at least one element with the specified value, use the filter { <field><value> } where <value> is the element value.

db.inventory.find( { tags: "red" } )

Q. How to find MongoDB records where array field is not empty?

db.inventory.find({ pictures: { $exists: true, $ne: [] } })

Q. How to get the last N records from find?

// Syntax
db.<CollectionName>.find().sort({$natural:-1}).limit(value)
 
 
// Example
db.employee.find().sort({$natural:-1}).limit(100)

Q. Explain relationships in mongodb?

Relationships in MongoDB are used to specify how one or more documents are related to each other. In MongoDB, the relationships can be modelled either by Embedded way or by using the Reference approach. These relationships can be of the following forms:

  • One to One
  • One to Many
  • Many to Many

Example: Let us consider the case of storing addresses for users. So, one user can have multiple addresses making this a 1:N relationship.

User Collection

{
   "_id":ObjectId("52ffc33cd85242f436000001"),
   "name": "Alex K",
   "contact": "987654321",
   "dob": "01-01-1990"
}

Address Collection

{
   "_id":ObjectId("52ffc4a5d85242602e000000"),
   "building": "22 A, Indiana Apt",
   "pincode": 123456,
   "city": "Los Angeles",
   "state": "California"
} 

1. Modeling Embedded Relationships

In the embedded approach, we will embed the address document inside the user document.

> db.users.insert({
        {
                 "_id":ObjectId("52ffc33cd85242f436000001"),
                 "contact": "987654321",
                 "dob": "01-01-1991",
                 "name": "Alex K",
                 "address": [
                         {
                                  "building": "22 A, Indiana Apt",
                                  "pincode": 123456,
                                  "city": "Los Angeles",
                                  "state": "California"
                         },
                         {
                                  "building": "170 A, Acropolis Apt",
                                  "pincode": 456789,
                                  "city": "Chicago",
                                  "state": "Illinois"
                         }
                 ]
        }
})

This approach maintains all the related data in a single document, which makes it easy to retrieve and maintain. The whole document can be retrieved in a single query such as −

>db.users.findOne({"name":"Alex K"},{"address":1})

The drawback is that if the embedded document keeps on growing too much in size, it can impact the read/write performance.

2. Modeling Referenced Relationships

This is the approach of designing normalized relationship. In this approach, both the user and address documents will be maintained separately but the user document will contain a field that will reference the address document’s id field.

{
   "_id":ObjectId("52ffc33cd85242f436000001"),
   "contact": "987654321",
   "dob": "01-01-1991",
   "name": "Alex K",
   "address_ids": [
      ObjectId("52ffc4a5d85242602e000000"),
      ObjectId("52ffc4a5d85242602e000001")
   ]
}

With this approach, we will need two queries: first to fetch the address_ids fields from user document and second to fetch these addresses from address collection.

>var result = db.users.findOne({"name":"Alex K"},{"address_ids":1})
>var addresses = db.address.find({"_id":{"$in":result["address_ids"]}})

Q. What is use of capped collection in MongoDB?

Capped collections are fixed-size collections that support high-throughput operations that insert and retrieve documents based on insertion order. Capped collections work in a way similar to circular buffers: once a collection fills its allocated space, it makes room for new documents by overwriting the oldest documents in the collection.

Capped collections restrict updates to the documents if the update results in increased document size. Since capped collections store documents in the order of the disk storage, it ensures that the document size does not increase the size allocated on the disk. Capped collections are best for storing log information, cache data, or any other high volume data.

Example:-

>db.createCollection( "log", { capped: true, size: 100000 } )
 
 
// specify a maximum number of documents for the collection
>db.createCollection("log", { capped: true, size: 5242880, max: 5000 } )
 
 
// check whether a collection is capped or not
>db.cappedLogCollection.isCapped()
 
 
// convert existing collection to capped
>db.runCommand({"convertToCapped": "posts", size: 10000})
 
 
// Querying Capped Collection
>db.cappedLogCollection.find().sort({$natural: -1})

Q1) Compare MongoDB and Cassandra

MongoDB:

  • data mode are document
  • database scalability is read only
  • query of the data is multi-index

Cassandra:

  • data mode are big table like
  • database scalability is write only
  • query of the data is using key or scana

Q2) what make magodb best?

it is consider has nosql database  because documented oriented (do).

Q3) When do we use Namespace in MongoDB?

in  database hte namespace is used

Q4) when an index does not fit into RAM?

index is very huge then index will not fit to RAM.

Q5) If you remove an object attribute, is it deleted from the database?

yes when the object attribute is delete then the object will be drop

Q6) Define MongoDB.

it th DO database which use in high availability and it is dynamic schema loction

Q7) What are the key features of mongodb?

  • high perform
  • high availability
  • automatic scaling,

Q8) what is meant by CRUD?

create read update delete

Q9)What is sharing in MongoDB?

the process of storing the record in multiple Machine is know has sharing.

Q10) How can you see the connection used by Mongos?

Mongos use db_adminCommand (“connPoolStats”);

Q11) Explain what is a replica set?

A replica set is the group of magodb instance which is host in same data set

Q12) How replication works in MongoDB?

the process of synchronization across the multiple server os know has replication.

Q13) While creating Schema in MongoDB what are the points need to be taken in consideration?

below are the following point need to be take care while carating the schema the combine objects into one document if you use them together for most frequent use cases optimize your schema

Q14) What is the syntax to create a collection?

syntax.
db.create Collection(name,options)

Q15) What is the syntax to drop a collection?

syntax:
drop collection in MongoDB is db.collection.drop()

Q16) Mention what is Object ld composed of?

  • Timestamp
  • Client machine ID
  • Client process ID
  • byte incremented counter

Q17) Mention what is the command syntax for inserting a document?

syntax :
database.collection.insert (document).

Q18) What is the command syntax that tells you whether you are on the master server or not? And how many master does MongoDB allow?

  • Command syntax
  • isMaster()

syntax
db._adminCommand(“connPoolStats.”)

Q20) Mention what is the basic syntax to use index in MongoDB?

syntax :
>db.COLLECTION_NAME.ensureIndex ( {KEY:1} ).

Q21)Explain what is GridFS in MongoDB?

while  storing and retrieving large files such as images.

Q22) What are alternatives to MongoDB?

  • Cassandr
  • CouchDB
  • Redis
  • Riak

Q23) What kind of NoSQL database MongoDB is?

It is a document oriented database.

Q24) Which all languages can be used with MongoDB?

c,java,c++

Q25) How is MongoDB better than other SQL databases?

it Permits  highly flexible and scalable document structure. does not support such relationships.

Q26) Does MongoDB need a lot of RAM?

it can run on small amount of data because it is dynamic space are allocated and re-allocated.

Q27) What is Mongo DB?

It is an open source database and prominent NOSQL database.

Q28)     What are all the advantage of MongoDB?

  • It is a Schema less.
  • Structure of a single object is clear.
  • No complex joins.
  • Easy of scale-out

Q29) How to create the database in Mongo DB?

Use Database name
Example: Use MYDB

Q30) How to show the entire database?

Show dbs

Q31) What are the datatypes Mongo DB supports?

String, Integer, Boolean, Double, Array, Timestamp, Date, Regular expression

Q32) How to insert document in Mongo DB collection?

Db.dbname.insert(document)

Q33) How to display all the documents?

Db.dbname.find()

Q34) What is the purpose of pretty () method?

Pretty () method used to display in formatted way.

Q35) What is the use of limit ()?

It will used to limit the value display from the documents.
DB.DBNAME.find ().limit (number)

Q36) What are all the Aggregate function in Mongo DB?

Sum, Avg, Min, Max, Push, addToSet, first, last

Q37) What is replication and why we need?

It is the process of synchronizing data across multiple server. It provides redundancy and increases data availability with multiple copies of data on different database server.WHY: To keep data safe, High availability of data, disaster recovery, No downtime for maintenance.

Q38) What is the syntax of sort() method?

db.COLLECTION_NAME.find().sort({KEY:1})

Q39) What is CRUD?

CRUD operations are Create, Read, Update, Delete.

Q40) What is the syntax to drop the collections?

Db.collection.drop()

Are You Interested in MongoDB Course ? Click here

Q41) What is embedded documents?

Embedded documents are received while they were small, given the relations between the related data has been written in one body.

Q42) Define application level encryption.

Application Level Encryption provides encryption or per-per-written from the field in the application layer.

Q43) The encryption storage?

MongoDB encryption encrypts data stored on any storage or processing by operating system may not be able to access protected data.

Q44) When everything is in no way sufficient data to get extended to multi-cut?

That stands in a few MongoDB collection. Therefore, the list is kept in a lump of dough of all substances, it is either in size. It is only when there is additional time slot, there will be no piece of information was a few choices, but the lump is more than 1, data is far from a lot of slices and can be extended up to 64 MB.

Q45) The judge in the MongoDB and Couchbase and CouchbaseDB?

When the common segment DB DB is Couchbase Couchbase Brunfelsia necessary in many ways, crossing points, all of which differ in the form of ecological duplications etc. As to the execution

Q46) Miâ on how we use MongoDB?

By sequencing of database, and the names of the pages linked from a specified collection is used.

Q47) If you remove an object attribute database wipes?

So deleted. It is better to be safe to remove the attribute.

Q48) How can we move into the old directory file moveChunk?

Since, however, the present and the old files are converted to the backup file is moved at the time of the acquisition moveChunk directory space.

Q49) Explain the situation with the index does not fit in RAM?

MongoDB learned from the experts? Enroll today

Q50) What MongoDB will provide consistency?

The writer makes use of MongoDB is he that readeth, and the bolts of it, after allowing to access one considers arbitrary or that any one that my readers may at the same time as the collection of a database. And it always brings access to private and hated by others.

Q51) Why did not MongoDB 32-bit system because he chose?

32 bit candidate for a non-Brunfelsia DB is contained, that means running 32 bit with the MongoDB server, information and indexes require 2 GB. 32-bit, so it is not the only way to enter my thoughts.

Q52) How does working on Journaling MongoDB?

There is nothing memory Journaling saved. The book on-disk files are really useful to have said that the route habitual. DbPath interior is designed in the Journal subdirectory MongoDB.

Q53) How can we separate cursors connection with the write injustice?

Snapshot () method is used to separate them from coming in with cursors writes. Here is a list of query and make sure everyone comes to be, and the manner of his mother tongue, there has been only to look at the article.

Q54) Define MongoDB.

It may be a document is to be oriented database of speech, with which the top of their minds to ease of scalability and easy to get high performance. The Scheme supports dynamic policy.

Q55) Explain the image set.

I have to put the example of which is the group made up of Brunfelsia same knowledge of the set. To kill, and I need to provide high availability redundancy is the image of, and in the production of all of the deployments.

Q56) What are the key features of mongodb?

3 and of the sea There are, however, latae sententiae, which are mongodb scaling: High performance and high availability.

Q57) The Crud?

Mongodb provides Crud are created, Read, Update, Delete.
To learn more information about the MongoDB Crud click here.

Q58) The sharding?

Sharding to store data on multiple machines.

Q59) What is the sum of the MongoDB?

What matters are aggregations process data records and return the results of counting.

Q60) To define the nominal distance mongodb?

And what is the name of the collection database.

Become a MongoDB Certified Expert in 25Hours

Q61)Syntax is used to create a collection mongodb?

db.createCollection (name, options) is used to create a collection mongodb.
Syntax collection.

Q62) That is to drop the mongodb?

db.collection.drop () is a collection to drop the mongodb.

Q63) Explain Infection.

Infection by more synchronous processing of data servers.

Q64) What is the use of index mongodb?

You can read a thing often used to provide a guideline for the high performance of queries.

Q65) The government should be inserted here because it is used?

database.collection.insert (document) is used for inserting the document.

Q66) What is the use of GridFS mongodb?

GridFS as I hear, is used for storage and for the most retrieving files, images, video files.

Q67) Journaling used?

Journaling is the use of the back of the mongodb to be saved.

Q68) That the government used to bond?

db_adminCommand ( “connPoolStats”); See the connection is not used.

Q69)Define the image killing?

The first things to write replicas but embraced the culture.

Q70) Define secondary image killing.

Secondaries (page 565) Brand apply for the primary, and op oplog.

Q71) Select the MongoDB equivalent query for the below SQL query – INSERT INTO employee (eid, age, salary) VALUES (763357, 45, 56489.40);

employee.insert( { eid: 763357, age: 45, salary: 56489.40 } )

 Q72) Identify the invalid statement

employee.insertMany( { [ emp_id:1, ename:”AAA” ] } )

 Q73) An “inventory” collection has documents stored in MongoDB in the following format:

{_id:1,  status: “available”,items: [ { sku:”006548e8″, details: {……} }, { sku:”0067458e8″, details: {……}  }  ], stocklevel:35, seller: “aaa” }

 Which of the following commands can be used to find all the documents in the “inventory” collection having stocklevel from 20 to 50? [20 and 50 inclusive]

inventory.find( { $nor: [ { stocklevel: { $lt:20 } },{ stocklevel:{ $gt:50 } } ] } ), db. inventory.find ( { stocklevel : { $gte: 20, $lte: 50 } } )

 Q74) Given the following documents in the electronics collection:

{ _id: 1, item: “oven”, price: 14000,quantity: 5 }

{ _id: 2, item: “LCD”, price: 48000, quantity: 10 }

{ _id: 3, item: “refrigerator”, price: 25000, quantity: 4 }

{ _id: 4, item: “LCD”, price: 56000, quantity: 3 }

{ _id: 5, item: “LCD”, price: 20000, quantity: 9 }

  What is the result of the below operation?

 db.electronics.update( {item : “LCD”, quantity : { $gte : 5 } },  { $set : { HD : “full HD” }, $inc : { price : 8000 } } )

Updates only the first matching document

 Q75) What would be the result of running the below query? – employee_profiles.deleteOne(   {‘unit’: ‘ETA’})

Only the first matching document is deleted

 Q76) The aggregation query in MongoDB that will sort the collection with ename field ascending.

employee.aggregate( [ { $sort: {ename:1} } ] )

 Q77) The command that creates an index on the quantity field, descending

inventory.createIndex( { “stock.quantity”:-1 } )

Q78) What is MongoDB?

MongoDB is a document-based database which is highly scalable, and offers better performance. Built around JSON-like documents, document databases are both natural and flexible for developers to work with.

Q79) How it is different from RDBMS?

  • Simple Data Model: Faster and Easier for Developers
  • Distributed: Resilient and Globally Scalable
  • Flexible Schema: Dynamically Adapt to Change
  • Universal: JSON Documents are Everywhere
  • Powerful: Query Data Anyway You Need

Q80) How much easier are document to work with SQL Tables?

RELATIONAL

IDFirstNameLastNameCell 
1AjayNadargi123456 
     
IDuserid Designation 
101 Tester   
111 Developer   
      
IDuserid name version
201 Project1 1.0.1
211 Project2 2.2.3
      
IDuserid make year
301 Shree 2018
311 Varad 2019

MONGODB

{

FirstName : “Ajay”,

LastName : “Nadargi”,

Cell : 123456,

Designation : [ “Tester”, “Developer” ],

Projects : [

{ name : “Project1” , version : 1.0.1 },

{ name : “Project2” , version : 2.2.3 }

],

Makers : [

{ make : “Shree” , year : 2018 },

{ make : “Varad” , version : 2019 }

]

}

Become a MongoDB Expert with Certification in 25hours

Q81) Need to run MongoDB?

  • High availability through built-in replication and failover
  • Horizontal scalability with native sharding
  • End-to-end security
  • Native document validation and schema exploration with Compass
  • Management tooling for automation, monitoring, and backup
  • Fully elastic database as a service with built-in best practices

Q82) Which types of NoSQL Databases?

  • Document databases store data in documents similar to JSON (JavaScript Object Notation) objects.
  • Key-value databases are a simpler type of database where each item contains keys and values.
  • Wide-column stores store data in tables, rows, and dynamic columns.
  • Graph databases store data in nodes and edges.

 Q83) How to start mongodb server/ instance?

  • mongod
  • mongod –dbpath /var/lib/mongo
  • mongod –port 27018
  • mongod –dbpath C:\Aj\data\db
  • mongod –logpath C:\Aj\logs\mongodb.log
  • mongod –port 27018 –dbpath C:\Aj\data\db –logpath C:\Aj\logs\mongodb.log — smallfiles
  • mongo –host mongodb0.example.com:27017

Q84) What is Bulk Write Operations?

  • MongoDB provides clients the ability to perform write operations in bulk. Bulk write operations affect a single
  • The collection.bulkWrite() method provides the ability to perform bulk insert, update, and remove operations. MongoDB also supports bulk insert through the db.collection.insertMany().
  • Bulk write operations can be either ordered or unordered.

Q85) Explain MongoDB CRUD Operation?

In MongoDB CRUD nothing but

  • Create Operations
  • Read Operations
  • Update Operations
  • Delete Operations

Create Operations 

  • Create or insert operations add new documents to a If the collection does not currently exist, insert operations will create the collection.
  • MongoDB provides  the  following  methods  to  insert  documents  into a collection:
    • collection.insertOne()
    • collection.insertMany()

Read Operations 

  • Read operations retrieves documents from a collection; e. queries a collection for documents. MongoDB provides the following methods to read documents from a collection:
    • collection.find()

Update Operations 

  • Update operations modify existing documents in a MongoDB provides the following methods to update documents of a collection:
    • collection.updateOne()
    • collection.updateMany()
    • collection.replaceOne()

Delete Operations

  •  Delete operations remove documents from a collection. MongoDB provides the following methods to delete documents of a collection:
    • collection.deleteOne()
    • db.collection.deleteMany()

Q86) How to create a database and a collection?

If a database does not exist, MongoDB creates the database when you first store data for that database. If a collection does not exist, MongoDB creates the collection when you first store data for that collection.

As such, you can switch to a non-existent database (use <dbname>) and perform the following operation:

  • use myCompanyDB
  • db.employee.insertOne( { id: 1 } )
  • db.department.createIndex( { dept_id: 1 } )

Q87) How do write operations affect indexes?

Write operations may require updates to indexes: If a write operation modifies an indexed field, MongoDB updates all indexes that have the modified field as a key. Therefore, if your application is write-heavy, indexes might affect performance.

Q88) How find the size of an index?

The db.collection.stats() includes an indexSizes document which provides size information for each index on the collection.Depending on its size, an index may not fit into RAM. An index fits into RAM when your server has enough RAM available for both the index and the rest of the working set.

Q89) What kind of replication does MongoDB support?

MongoDB supports replica sets, which can have up to 50 nodes.

Q90) What is a replica set?

The group of instances which host similar data set is known as a replica set. Two nodes are present in a replica set, one is secondary and the other is primary, where data is replicated from primary and sent to the secondary node.

Q91) Is it normal for replica set members to use different amounts of disk space?

Yes. Factors including: different oplog sizes, different levels of storage fragmentation, and MongoDB’s data file pre-allocation can lead to some variation in storage utilization between nodes. Storage use disparities will be most pronounced when you add members at different times.

Q92) How does mongos use connections?

Each mongos instance maintains a pool of connections to the members of the sharded cluster. Client requests use these connections one at a time; i.e. requests are not multiplexed or pipelined.

When client requests complete, the mongos returns the connection to the pool. These pools do not shrink when the number of clients decreases. This can lead to an unused mongos with a large number of open connections. If the mongos is no longer in use, it is safe to restart the process to close existing connections.

To return aggregated statistics related to all of the outgoing connection pools used by the mongos, connect a mongo shell to the mongos with , and run the connPoolStats command: db.adminCommand(“connPoolStats”);

Q93) Is sharding appropriate for a new deployment?

Sometimes. However, if your data set fits on a single server, you should begin with an unsharded deployment as sharding while your data set is small provides little advantage .

 Q94) What does sharding mean in MongoDB?

Sharding is a process of storing data records among one or more machines applied by MongoDB to meet the demands of data growth. It forms a horizontal partition in the database and each partition is known as database shard or a shard.

Q95) What is a storage engine?

A storage engine is the part of a database that is responsible for managing how data is stored, both in memory and on disk. Many databases support multiple storage engines, where different engines perform better for specific workloads. For example, one storage engine might offer better performance for read-heavy workloads, and another might support a higher throughput for write operations.

Q96) How can I check the size of a collection?

To view the statistics for a collection, including the data the db.collection.stats() method from the mongo shell. The following issues db.collection.stats() for the orders collection: db.orders.stats(); size, use example

Q97) How do I calculate how much RAM I need for my application?

With WiredTiger, MongoDB utilizes both the WiredTiger internal cache and the filesystem cache. The default WiredTiger internal cache size is the larger of either:

50% of (RAM – 1 GB), or 256 MB.

For example, on a system with a total of 4GB of RAM the WiredTiger cache will use 1.5GB of RAM (0.5 * (4 GB – 1 GB) = 1.5 GB). Conversely, a system with a total of 1.25 GB of RAM will allocate 256 MB to the WiredTiger cache because that is more than half of the total RAM minus one gigabyte ( 0.5 * (1.25 GB – 1 GB) = 128 MB < 256 MB)

Q98) What is the role of profiler in MongoDB?

The role of a MongoDB profiler is to show the performance and analyze the characteristics of every operation of the database. By using the profiler, you will find all the queries which are slower than usual.

Q99) MongoDB database support foreign-key and primary-key relationship?

No, by default, MongoDB doesn’t support foreign key or a primary key relationship.

Q100) How does MongoDB offer consistency?

To provide consistency, MongoDB makes use of reader-writer locks to allow readers to simultaneously access any collection like a database but it always offers private access to single writers.

Q101) In MongoDB what is Objecld composed of?

ObjectId(<hexadecimal>) Returns a new ObjectId value.

The 12-byte ObjectId value consists of:

  • a 4-byte timestamp  value,  representing  the  ObjectId’s  creation,  measured  in seconds since the Unix epoch
  • a 5-byte random value
  • a 3-byte incrementing counter, initialized to a random value

Q102) In MongoDB, which command can be used to provide all information of a query plan?

The explain() command is used to provide information of all the query plans. The possible models are as follows:

  • ‘queryPlanner’,
  • ‘executionStats’,
  • ‘allPlansExecution’

Q103) What feature in MongoDB is used to do safe backups?

To save backups of the old files “Journaling” feature is used in MongoDB databases.

Q104) Mongo complex sorting?

Sort queries in MongoDB by multiple fields, e.g.,db.collection.find().sort({a:1,b:-1}).

Q105) Which utility used for backup and restore?

mongodump provides a the mongod instances, while mongorestore makes BSON dump files into JSON. it method possible for creating BSON dump files from to restore these  dumps. bsondump converts mongoimport provides a method for taking data in JSON, CSV, or TSV and importing it into a mongod instance. mongoexport provides a method to export data from a mongod instance into JSON, CSV, or TSV.

Q106) MongoDB is supported by

  1. PHP
  2. Python
  3. All the mentioned
  4. Perl

Ans: All the mentioned

Q107) Different MongoDB Backup Methods?

  • Back Up with Atlas
  • Back Up with MongoDB Cloud Manager or Ops Manager o Back Up by Copying Underlying Data Files
  • Back Up with mongodump

Q108) How to check the MongoDB Performance?

  • Locking Performance
  • Number of Connections
  • Database Profiling
  • Full Time Diagnostic Data Capture

Q109) What are the MongoDB Configuration and Maintenance?

Run-time Database Configuration 

  • Outlines common MongoDB configurations and examples of best-practice configurations for common use cases.

Upgrade to the Latest Revision of MongoDB 

  • Introduces the basic process for upgrading a MongoDB deployment between different minor release versions.

Manage mongod Processes 

  • Start, configure, and manage running mongod

Terminate Running Operations

  • Stop in progress MongoDB client operations using db.killOp() and maxTimeMS().

Rotate Log Files

  • Archive the current log files and start new ones.

Q110) Explain Mongo Security?

MongoDB provides various features, such as authentication, access control, encryption, to secure your MongoDB deployments.

Get MongoDB Online Training

Q111) How to create User in MongoDB?

use products

db.createUser( { user: “accountAdmin01”,

pwd: passwordPrompt(),  // Or “<cleartext password>”

customData: { employeeId: 12345 },

roles: [ { role: “clusterAdmin”, db: “admin” },

{ role: “readAnyDatabase”, db: “admin” }, “readWrite”] },

{ w: “majority” , wtimeout: 5000 } )

Q112) “Complete the following statement: _____________is a data structure (most commonly a B- tree) that stores the values for a specific column in a table”

  1. index
  2. stored procedure
  3. check
  4. table

Ans: index

Q113) “Which one of the SQL joins is represented by the following example:

SELECT P.ProductID,

P.Name,

P.ListPrice,

SOD.UnitPrice,

SnotOD.UnitPriceDiscount,

FROM Sales.SalesOrderDetail SOD

JOIN Production.Product P

ON SOD.ProductID = P.ProductID

WHERE SOD.UnitPrice> 1000

ORDER BY SOD.UnitPrice DESC”

  1. Inner Join
  2. Left Outer Join
  3. Right Outer Join
  4. None from the options

Ans: Inner Join

Q114) “State True of False:

Indexes are automatically created for Primary keys and Unique key constraints”

  • TRUE
  • FALSE

Ans: TRUE

Q115) “Complete the following statement: A ___________ is a query that is nested inside a SELECT, INSERT, UPDATE, or DELETE statement”

  1. subquery
  2. Inner Join
  3. Outer Join
  4. None from the options

Ans: subquery

Q116) “State True of False: Indexes help SQL Server retrieve the data quicker”

  1. TRUE
  2.  FALSE

Ans: TRUE

Q117) The integrity constrain “not null” specifies

  1. Nulls will not be allowed in the column
  2. Null will be allowed in a column
  3. can contain one and only one null
  4. none of the options

Ans: Nulls will not be allowed in the column

Q118) “Complete the Following Statements: A candidate key not chosen to be the Primary Key in a relation is called ______.”

  1. Alternate Key
  2. Alternative Key
  3. Foreign Key
  4. Super Key

Ans: Alternate Key

Q119) What does the term “the degree” of a relationship indicate?

  1. It is the number of participating entities in a relationship
  2. It indicates whether a relationship is one to many or many to many

Ans: It is the number of participating entities in a relationship

Q120) What kind of integrity does a foreign key represent?

  1. Entity Integrity
  2. Referential Inegrity
  3. User-defined Integrity
  4.  Domain check Integrity

Ans: Referential Inegrity

Q121) “Consider the following code snippet SELECT PRODUCT_NO,DESCRIPTION,SUM(PRICE * QTY) ‘Total Worth’ FROM PRODUCT GROUP BY PRODUCT_NO;”

  1. It will give an Error , and will not execute
  2. It will give the output as desired
  3. It will generate a warning but will also generate the output as desired
  4. It will crash sqlserver

Ans: It will give an Error , and will not execute

Q122) “Complete the following statement: The primary – foreign key relations are used to ____________”

  1. cross-reference database tables
  2. to index the database
  3. clean-up the database
  4. None from the options

Ans: cross-reference database tables

Q123) How many columns/attributes a single primary key can have?

  1. One
  2. Many
  3. Just two
  4. Zero

Ans: Many

Q124) Which SQL statement is used to update data in a database?

  1. MODIFY
  2. SAVE
  3. UPDATE
  4. SAVE AS

Ans: UPDATE

Q125) Which SQL statement is used to extract data from a database?

  1. OPEN
  2. SELECT
  3. EXTRACT
  4. GET

Ans: SELECT

Q126) Which of the following command provides you with a list of all the databases in MongoDB?

  1. show dbs
  2. show databases
  3. show all dbs
  4. None of the above.

Ans: show dbs

Q127) „$set‟ is used for ___________.

  1. Delete
  2. Insert
  3. Update

Ans: Update

Q128) MongoDB supports indexes just like any other relational database.

  1. True
  2. False

Ans: True

Q129) Which of the following command creates an index, where mobile_no is a field in the collection employees

  1. employees.SetIndex( { “mobile_no”: 1 } )
  2. employees.ensureIndex( { “mobile_no”: 1 } )
  3. SetIndex( { “mobile_no”: 1 } )

Ans: employees.ensureIndex( { “mobile_no”: 1 } )

Q130) Which of the following command is correct when you want to fetch documents form collection demo, where value of a field „interest‟ is null?

  1. demo.find( { “interest : null” } )
  2. demo.find( { “interest” : null } )
  3. demo.find().sort( { “interest” : null } )

Ans: demo.find( { “interest” : null } )

Q131) MongoDB documents are represented as _____.

  1. JSON
  2. XML
  3. DOCUMENT

Ans: JSON

Q132) Which of the following is equivalent to this: select first_name,salary from employees where designation=”Manager”; Assume that there are three columns first_name,salary,date_of_join.

  1. employees.find({“designation:Manager”},{“date_of_join” : 1})
  2. employees.find({“designation:Manager”},{“date_of_join” : 0})
  3. employees.find({“designation”:”Manager”},{“date_of_join” : 0})

Ans: employees.find({“designation”:”Manager”},{“date_of_join” : 0})

Q133) Which one of the following answers is equivalent to this SQL command: Select * from employees where date_of_join=”16/10/2010? and designation=”Manager” order by salary desc;

  1. employees.find({“date_of_join : 16/10/2010″,”designation:Manager”}).sort({“salary:-1”})
  2. employees.find({“date_of_join” :”16/10/2010″,”designation”:”Manager”}).sort({“salary”:-1})
  3. employees.find().sort({“date_of_join” : “16/10/2010″,”designation”:”Manager”}).sort({“salary”:-1})

Ans: employees.find({“date_of_join” :”16/10/2010″,”designation”:”Manager”}).sort({“salary”:-1})

Q135) „mongoimport‟ command is used for ___________.

  1. Multiple command import
  2. Multiple command insertion
  3. Provides a route to import content from a JSON, CSV, or TSV export created by mongoexport

Ans: Provides a route to import content from a JSON, CSV, or TSV export created by mongoexport

Q136) MongoDB supports query joins between collections.

  1. False
  2. True

Ans: False

Q137) Which of the following is correct command to update?

  1. books.update( { item: “book”, qty: { $gt: 7 } }, { $set: { x: 5 }, $inc: { y: 8} } , { multi: true} )
  2. books.update( { item: “book”, qty: { $gt: 7 } }, { $set: { x: 5 }, $inc: { y: 8} } )
  3. db.books.find().update( { item: “book”, qty: { $gt: 7 } }, { $set: { x: 5 }, $inc: { y: 8} } )

Ans: books.update( { item: “book”, qty: { $gt: 7 } }, { $set: { x: 5 }, $inc: { y: 8} } )

Q138) What does the following command do? db.demo.find({“extra.community_name” : “Rock”,”extra.friends.valued_friends_id”:”Jhon”})

  1. Fetch documents from the collection “demo” which contain the value of “community_name” “Rock’ and “valued_friends_id” is “Jhon”
  2. Fetch documents from the collection “demo” which contain the value of “community_name” is “Rock” and “valued_friends_id” which is under the “friends” is “Jhon” and all the said is under “extra” of an JSON style object,

Ans: Fetch documents from the collection “demo” which contain the value of “community_name” is “Rock” and “valued_friends_id” which is under the “friends” is “Jhon” and all the said is under “extra” of an JSON style object

Q139) Which one of the following is equivalent to Select * from employees order by salary

  1. employees.find().sort({“salary”:1})
  2. employees.sort({“salary”:1})
  3. employees.find().sort({“salary:1”})

Ans: employees.find().sort({“salary”:1})

Q140) Which of the following command is correct when you want to fetch documents from collection where only employees whose salary is 7500 and date of join is either of the given dates would come?

  1. employees.find().sort({ “salary” : “7500” , $or : [ { “date_of_join” : “17/10/2009” }; { “date_of_join” : “27/4/2010” } ] } );
  2. employees.find({ “salary” : “7500” , ($or : [ { “date_of_join” : “17/10/2009”, “date_of_join” : “27/4/2010” } ] } ));
  3. employees.find({ “salary” : “7500” , $or : [ { “date_of_join” : “17/10/2009” }, {“date_of_join” : “23/12/2009” } ] } );

Ans: employees.find({ “salary” : “7500” , ($or : [ { “date_of_join” : “17/10/2009”, “date_of_join” : “27/4/2010” } ] } ));

Basic Interview Questions

1. Compare MongoDB with Cassandra.

CriteriaMongoDBCassandra
Data ModelDocumentBigtable like
Database scalabilityReadWrite
Querying of dataMulti-indexedUsing Key or Scan

To have a detailed comparison between MongoDB and Cassandra, check out Cassandra Versus MongoDB!

2. What makes MongoDB the best?

MongoDB is considered to be the best NoSQL database because of its following features:

  • Document-oriented (DO)
  • High performance (HP)
  • High availability (HA)
  • Easy scalability
  • Rich query language

3. How to do transactions/locking in MongoDB?

MongoDB does not use conventional locking with reduction as it is planned to be light, high-speed, and knowable in its presentation. It can be considered as parallel to the MySQL MyISAM auto entrust sculpt. With the simplest business sustain, performance is enhanced, particularly in a structure with numerous servers.

4. When and to what extent does data get extended to multi-slice?

MongoDB scrap stands on a collection. So, an album of all substances is kept in a lump or mass. Only when there is an additional time slot, there will be more than a few slice data achievement choices, but when there is more than one lump, data gets extended to a lot of slices and it can be extended to 64 MB.

5. Compare MongoDB with Couchbase and CouchbaseDB.

Although MongoDB, Couchbase and Couchbase DB are common in many ways, still they are different in the case of necessities for the execution of the model, crossing points, storage, duplications, etc.

Certification in Bigdata Analytics

6. When do we use a namespace in MongoDB?

During the sequencing of the names of the database and the collection, the namespace is used.

7. If you remove an object attribute, is it deleted from the database?

Yes, it is deleted. Hence, it is better to eliminate the attribute and then save the object again.

8. How can we move an old file into the moveChunk directory?

Once the functions are done, the old files are converted to backup files and moved to the moveChunk directory at the time of balancing the slices.

9. Explain the situation when an index does not fit into RAM.

When an index is too huge to fit into RAM, then MongoDB reads the index, which is faster than reading RAM because the indexes easily fit into RAM if the server has got RAM for indexes, along with the remaining set.

10. How does MongoDB provide consistency?

MongoDB uses the reader–writer locks, allowing simultaneous readers to access any supply like a database or a collection but always offering private access to single writes.

11. Why is MongoDB not chosen for a 32-bit system?

Mongo DB is not considered as a 32-bit system because for running the 32-bit MongoDB, with the server, information and indexes require 2 GB. That is why it is not used in 32-bit devices.

12. How does Journaling work in MongoDB?

Write operations are saved in memory while journaling is going on. The on-disk journal files are really dependable for the reason that the journal writes are habitual. Inside dbPath, a journal subdirectory is designed by MongoDB.

13. How can you isolate the cursors from intervening with the write operations?

The snapshot() method is used to isolate the cursors from intervening with writes. This method negotiates the index and makes sure that each query comes to any article only once.

14. Define MongoDB.

It is a document-oriented database that is used for high availability, easy scalability, and high performance. It supports the dynamic schema design.

15. Explain the replica set.

It is a group of mongo instances that maintains the same dataset. Replica sets provide redundancy and high availability and are the basis for all production deployments.

16. What are the key features of MongoDB?

There are three main features of MongoDB:

  • Automatic scaling
  • High performance
  • High availability

17. What is CRUD?

MongoDB provides CRUD operations:

  • Create
  • Read
  • Update
  • Delete

Click here to learn more about MongoDB CRUD Operations in our MongoDB Tutorial!

18. What is Sharding?

In MongoDB, sharding means to store data on multiple machines.

19. What is Aggregation in MongoDB?

In MongoDB, aggregations are operations that process data records and return computed results.

20. Define Namespace in MongoDB.

It is the concatenation of the collection name and the name of the database.

Intermediate Interview Questions

21. Which syntax is used to create a Collection in MongoDB?

We can create a collection in MongoDB using the following syntax:

db.createCollection(name,options)

22. Which syntax is used to drop a Collection in MongoDB?

We can use the following syntax to drop a collection in MongoDB:

db.collection.drop()

23. Explain Replication.

Replication is the process of synchronizing data across multiple servers.

24. What is the use of an Index in MongoDB?

In MongoDB, indexes provide high-performance read operations for frequently used queries.

If you have any doubts or queries related to MongoDB, get them clarified from MongoDB Experts on our MongoDB Community!

25. Which command is used for inserting a document in MongoDB?

The following command is used for inserting a document in MongoDB:

database.collection.insert (document)

26. What is the use of GridFS in MongoDB?

GridFS is used for storing and retrieving large files, such as audio, image, and video files.

27. What is the use of Journaling in MongoDB?

Journaling is used for safe backups in MongoDB.

28. Which command is used to see a connection?

We can use the following command to see the connection:

db_adminCommand (“connPoolStats”)

29. Define the primary Replica set.

The primary replica set accepts all write operations from clients.

30. Define the secondary Replica sets.

The secondaries replicate the primary replica set’s oplog and apply the operations to their datasets such that the secondaries’ datasets reflect the primary’s dataset.

31. What is the use of Profiler?

Profiler is used to show the performance characteristics of every operation against the database.

Become a Big Data Architect

32. What type of data is stored by MongoDB?

MongoDB stores data in the form of documents, which are JSON-like field and value pairs.

33. What is the purpose of Replication?

Replication provides redundancy, and it increases data availability.

34. What are Embedded documents?

Embedded documents capture relationships between data by storing related data in a single document structure.

35. Define the application-level Encryption.

The application-level encryption provides encryption on a per-field or per-document basis within the application layer.

36. What is Storage Encryption?

Storage encryption encrypts all MongoDB data on storage or on the operating system to ensure that only authorized processes can access the protected data.

37. Which method is used to create an index?

The createIndex() method is used to create an index.

38. What is Replica set oplog?

The oplog records all operations that modify the data in the replica set.

39. What is Vertical Scaling?

Vertical scaling adds more CPU and storage resources to increase capacity.

40. Define Horizontal Scaling.

Horizontal scaling divides the dataset and distributes data over multiple servers, or shards.

Advanced Interview Questions

41. What are the components of the Sharded cluster?

The sharded cluster has the following components:

  • Shards
  • Query routers
  • Config servers

42. Which command is used to create a database?

To create a database, we can use the Database_Name command.

43. Which command is used to drop a database?

The db.dropDatabse() command is used to drop a database.

44. What is the use of the pretty() method?

The pretty() method is used to show the results in a formatted way.

45. Which method is used to remove a document from a collection?

The remove() method is used to remove a document from a collection.

46. Define MongoDB Projection.

Projection is used to select only the necessary data. It does not select the whole data of a document.

47. What is the use of the limit() method?

The limit() method is used to limit the records in the database.

48. What is the syntax of the limit() method?

The syntax of the limit() method is as follows:

>db.COLLECTION_NAME.find().limit(NUMBER)

49. What is the syntax of the sort() method?

In MongoDB, the following syntax is used for sorting documents:

>db.COLLECTION_NAME.find().sort({KEY:1})

50. Which command is used to create a backup of the database?

The mongodump command is used to create a backup of the database.

51. What is a Collection in MongoDB?

In MongoDB, a collection is a group of MongoDB documents.

52. What is the use of the db command?

The db command gives the name of the currently selected database.

53. Which method is used to update documents into a collection?

The update() and save() methods are used to update documents into a collection.

54. What is the syntax of the skip() method?

The syntax of the skip() methopd is as follows:

>db.COLLECTION_NAME.find().limit(NUMBER).skip(NUMBER)

55. Which command is used to restore the backup?

The mongorestore command is used to restore the backup.

56. What is the use of the dot notation in MongoDB?

MongoDB uses the dot notation to access the elements of an array and the fields of an embedded document.

57. Define Auditing.

Auditing provides administrators with the ability to verify that the implemented security policies are controlling the activity in the system.

58. Define the Aggregation pipeline.

The aggregation pipeline is a framework for performing aggregation tasks. The pipeline is used to transform documents into aggregated results.

59. Define MapReduce.

MapReduce is a generic multi-phase data aggregation modality that is used for processing quantities of data.

60. What is Splitting in MongoDB?

Splitting is a background process that is used to keep chunks from growing too large.

Learn new Technologies

61. Which language is used to write for MongoDB?

C++ is used for writing and implementing MongoDB.

62. In which format does MongoDB store data?

MongoDB uses collections to store data rather than tables.

63. What is the use of the save() method?

The save() method is used to replace the existing document with a new document.

64. What is MongoDB?

MongoDB (from humongous) is a cross-platform document-oriented database. Classified as a NoSQL database, MongoDB eschews the traditional table-based relational database structure in favor of JSON-like documents with dynamic schemas (MongoDB calls the format ‘BSON’), making the integration of data in certain types of applications easier and faster. Released under a combination of the GNU Affero General Public License and the Apache License, MongoDB is open-source.

MongoDB was first developed by the software company 10gen (now, MongoDB Inc.) in October 2007 as a component of a planned platform as a service product. Then, the company shifted to an open-source development model in 2009, with 10gen offering commercial support and other services. Since then, MongoDB has been adopted as backend software by a number of major websites and services, including Craigslist, eBay, Foursquare, SourceForge, Viacom, and the New York Times, among others. Currently, MongoDB is the most popular NoSQL database system.

For a better understanding of MongoDB, refer to this What is MongoDB? blog.

65. What is the use of MongoDB?

MongoDB is a relational database management system (RDBMS) replacement for web applications. So, when we have something close to RDBMS, MongoDB could be of good use.

It gives us the additional partition tolerance, which RDMBS doesn’t offer, but it has problems with availability. Nonetheless, if we want more scalability, MongoDB would be the right choice for us. It’s suitable for real-time analytics and high-speed logging, and it’s highly scalable as well. Craigslist uses MongoDB for archived posts.

66. What do you understand by NoSQL databases? Is MongoDB a NoSQL database? Explain.

Presently, the Internet is loaded with big data, big users, and so on that are becoming more complex day by day. NoSQL is the answer to all these problems; it is not a traditional database management system, not even a relational database management system (RDBMS).

NoSQL stands for ‘Not only SQL’, and it is a type of database that can handle and sort all types of unstructured, messy, and complicated data. It is just a new way to think about databases.

Yes, MongoDB is a NoSQL database.

67. What type of a DBMS is MongoDB?

MongoDB is a document-oriented DBMS.

68. What is the difference between MongoDB and MySQL?

Although both MongoDB and MySQL are free and open-source databases, there is a lot of difference between them in terms of data representation, relationships, transaction, querying data, schema design and definition, performance speed, normalization, and many more. To compare MySQL with MongoDB is like a comparison between relational and non-relational databases.

69. What is the use of MongoDB?

  •  MongoDB is typically used as the primary data store for operational applications with real-time requirements (i.e., low latency, high availability, etc.). MongoDB is generally a good fit for 60–80 percent of the applications we build today. MongoDB is easy to operate and scale in the ways that are hard if not impossible with relational databases.
  • MongoDB excels in many use cases where the relational databases aren’t a good fit, like applications with unstructured, semi-structured, and polymorphic data, as well as those with large scalability requirements or multi-datacenter deployments.
  • MongoDB may not be a good fit for some applications. For example, applications that require complex transactions (e.g., a double-entry bookkeeping system) and scan-oriented applications that access large subsets of the data mostly may not be a good fit for MongoDB. Also, MongoDB is not a drop-in replacement for legacy applications built around the relational data model and SQL.
  • Some common use cases of MongoDB include mobile apps, product catalogs, real-time personalization, content management, and applications delivering a single view across multiple systems.

70. What kind of a database is MongoDB?

MongoDB is a document-oriented DBMS. We can think of it as MySQL but with JSON-like objects comprising the data model, rather than RDBMS tables. Significantly, MongoDB supports neither joins nor transactions. However, it features secondary indexes, an expressive query language, atomic writes on a per-document level, and fully-consistent reads. Operationally, MongoDB offers the master–slave replication with automated failover and built-in horizontal scaling via automated range-based partitioning.

To learn more about MongoDB, check out Intellipaat’s MongoDB Tutorial!

71. Which language is MongoDB written in?

MongoDB is implemented in C++. However, drivers and client libraries are typically written in their own respective languages. Although, some drivers use C extensions for better performance.

72. What are the limitations of the 32-bit versions of MongoDB?

MongoDB uses memory-mapped files. When running a 32-bit build of MongoDB, the total storage size for the server, including data and indexes, is 2 GB. For this reason, we do not deploy MongoDB to production on 32-bit machines.

If we’re running a 64-bit build of MongoDB, there’s virtually no limit to the storage size. For production deployments, 64-bit builds and operating systems are strongly recommended.

73. While creating a schema in MongoDB, what are the points need to be taken into consideration?

While creating a schema in MongoDB, the points need to be taken care of are as follows:

  • Design our schema according to the user requirements
  • Combine objects into one document if we want to use them together; otherwise, separate them
  • Do joins while on write, and not when it is on read
  • For most frequent use cases, optimize the schema
  • Do complex aggregation in the schema

One thought on “MongoDB Interview Q&A

    Suyog Ketkar said:
    07/03/2022 at 12:18 pm

    That’s awesome. Thank you for the list of questions!
    Quite handy.

    Like

Leave a comment