mongodb questions
Categories:

10 Most Asked MongoDB Questions

MongoDB is a cross-platform document-oriented database program. Classified as a NoSQL database program, MongoDB uses JSON-like documents with the schema. The database’s ability to scale up with ease and hold very large amounts of data. MongoDB stores documents in collections within databases. And, it is one of the popular DBMS used by developers today. So, today we will be checking out the 10 most asked MongoDB questions.

10 Most Asked MongoDB Questions

Here is the list of MongoDB questions asked frequently by database engineers and developers. We came up with this list to make it easy for developers to solve their problems if they have any questions mentioned in the list. So, let’s begin.

1. How to query MongoDB with “like”?

Answer:

For this problem, you need to have the following command:

db.users.find({"name": /.*m.*/})

or, similar:

db.users.find({"name": /m/})

You’re looking for something that contains “m” somewhere (SQL’s ‘%‘ operator is equivalent to Regexp’s ‘.*‘), not something that has “m” anchored to the beginning of the string.

Note: MongoDB uses regular expressions which are more powerful than “LIKE” in SQL. With regular expressions, you can create any pattern that you imagine.

Alternative Answer:

  • PyMongo using Python
  • Mongoose using Node.js
  • Jongo, using Java
  • mgo, using Go

you can do:

db.users.find({'name': {'$regex': 'sometext'}})

2. How to drop a MongoDB database from the command line?

Answer:

You can drop a MongoDB database from the command line, like this:

mongo <dbname> --eval "db.dropDatabase()"

More info on scripting the shell from the command line here: https://docs.mongodb.com/manual/tutorial/write-scripts-for-the-mongo-shell/#scripting

Alternative Answer:

From the mongodb console:

> use mydb; 
> db.dropDatabase();

Alternatively, you can stop mongod and delete the data files from your data directory, then restart.

Hint: You can also move the data files to a sub folder, and delete them if you’re sure you no longer need them.

3. How to list all collections in the MongoDB shell?

Answer:

You can do as given below:

JavaScript (shell):

db.getCollectionNames()

Node.js:

db.listCollections()

Non-JavaScript (shell only):

show collections

The reason to call it non-JavaScript is because :

$ mongo prodmongo/app --eval "show collections"
MongoDB shell version: 3.2.10
connecting to: prodmongo/app
2016-10-26T19:34:34.886-0400 E QUERY    [thread1] SyntaxError: missing ; before statement @(shell eval):1:5

$ mongo prodmongo/app --eval "db.getCollectionNames()"
MongoDB shell version: 3.2.10
connecting to: prodmongo/app
[
    "Profiles",
    "Unit_Info"
]

If you really want that sweet, sweet show collections output, you can:

$ mongo prodmongo/app --eval "db.getCollectionNames().join('\n')"
MongoDB shell version: 3.2.10
connecting to: prodmongo/app
Profiles
Unit_Info

Other methods:

  • show collections
  • show tables
  • db.getCollectionNames()

To list all databases:

show dbs

To enter or use a given database:

use databasename

To list all collections:

show collections

Output:

collection1
collection2
system.indexes

(or)

show tables

Output:

collection1
collection2
system.indexes

(or)

db.getCollectionNames()

Output:

[ "collection1", "collection2", "system.indexes" ]

To enter or use given collection

use collectionname

4. How to use embed or reference in relationships?

Answer:

This is more an art than a science. The Mongo Documentation on Schemas is a good reference, but here are some things to consider:

  • Put as much in as possible The joy of a Document database is that it eliminates lots of Joins. Your first instinct should be to place as much in a single document as you can. Because MongoDB documents have structure, and because you can efficiently query within that structure (this means that you can take the part of the document that you need, so document size shouldn’t worry you much) there is no immediate need to normalize data like you would in SQL. In particular, any data that is not useful apart from its parent document should be part of the same document.
  • Separate data that can be referred to from multiple places into its own collection. This is not so much a “storage space” issue as it is a “data consistency” issue. If many records will refer to the same data it is more efficient and less error-prone to update a single record and keep references to it in other places.
  • Document size considerations MongoDB imposes a 4MB (16MB with 1.8) size limit on a single document. In a world of GB of data, this sounds small, but it is also 30 thousand tweets or 250 typical Stack Overflow answers or 20 flicker photos. On the other hand, this is far more information than one might want to present at one time on a typical web page. First, consider what will make your queries easier. In many cases, concern about document sizes will be premature optimization.
  • Complex data structures: MongoDB can store arbitrary deep nested data structures, but cannot search them efficiently. If your data forms a tree, forest, or graph, you effectively need to store each node and its edges in a separate document. (Note that there are data stores specifically designed for this type of data that one should consider as well) It has also been pointed out than it is impossible to return a subset of elements in a document. If you need to pick-and-choose a few bits of each document, it will be easier to separate them out.
  • Data Consistency MongoDB makes a trade-off between efficiency and consistency. The rule changes to a single document are always atomic, while updates to multiple documents should never be assumed to be atomic. There is also no way to “lock” a record on the server (you can build this into the client’s logic using, for example, a “lock” field). When you design your schema consider how you will keep your data consistent. Generally, the more that you keep in a document the better.

Additional Answer:

In general, embed is good if you have one-to-one or one-to-many relationships between entities, and reference is good if you have many-to-many relationships.

5. How to get the last N records in MongoDB?

Answer:

Assuming you have some id or date field called “x” you would do:

.sort()

db.foo.find().sort({x:1});

The 1 will sort ascending (oldest to newest) and -1 will sort descending (newest to oldest.)

If you use the auto-created _id field it has a date embedded in it, so you can use that to order by:

db.foo.find().sort({_id:1});

That will return back all your documents sorted from oldest to newest.

Natural Order

You can also use a Natural Order mentioned above …

db.foo.find().sort({$natural:1});

Again, using 1 or -1 depending on the order you want.

Use .limit()

Lastly, it’s good practice to add a limit when doing this sort of wide-open query so you could do either.

db.foo.find().sort({_id:1}).limit(50);

or

db.foo.find().sort({$natural:1}).limit(50);

6. Is there a way to tell Mongo to pretty print output?

Answer:

You can ask it to be pretty by following command.

db.collection.find().pretty()

Alternative Answer:

Also you can add

DBQuery.prototype._prettyShell = true

to your file in $HOME/.mongorc.js to enable pretty print globally by default.

Alternative Answer:

You can just do this on the CLI:

echo DBQuery.prototype._prettyShell = true >> ~/.mongorc.js

And it’s always going to output pretty results.

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

Answer:

If you have documents that don’t have the key, you can use:

ME.find({ pictures: { $exists: true, $not: {$size: 0} } })

MongoDB don’t use indexes if $size is involved, so here is a better solution:

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

Since MongoDB 2.6 release, you can compare with the operator $gt but could lead to unexpected results.

ME.find({ pictures: { $gt: [] } }

Alternative Answer:

You can also do as given below:

ME.find({pictures: {$exists: true, $not: {$size: 0}}})

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

Answer:

As favouriteFoods is a simple array of strings, you can just query that field directly:

PersonModel.find({ favouriteFoods: "sushi" }, ...);

But it is also recommended to make the string array explicit in your schema:

person = {
    name : String,
    favouriteFoods : [String]
}

The relevant documentation can be found here: https://docs.mongodb.com/manual/tutorial/query-arrays/

9. How do you rename a MongoDB database?

Answer:

Unfortunately, this is not a simple feature for us to implement due to the way that database metadata is stored in the original (default) storage engine. In MMAPv1 files, the namespace (e.g.: dbName.collection) that describes every single collection and index includes the database name, so to rename a set of database files, every single namespace string would have to be rewritten. This impacts:

  • the .ns file
  • every single numbered file for the collection
  • the namespace for every index
  • internal unique names of each collection and index
  • contents of system.namespaces and system.indexes (or their equivalents in the future)
  • other locations that may be missing

This is just to accomplish a rename of a single database in a standalone mongod instance. For replica sets the above would need to be done on every replica node, plus on each node every single oplog entry that refers this database would have to be somehow invalidated or rewritten, and then if it’s a sharded cluster, one also needs to add these changes to every shard if the DB is sharded, plus the config servers have all the shard metadata in terms of namespaces with their full names.

There would be absolutely no way to do this on a live system.

To do it offline, it would require re-writing every single database file to accommodate the new name, and at that point, it would be as slow as the current “copydb” command.

For more see See https://jira.mongodb.org/browse/SERVER-7

Alternative Answer:

You could do this:

db.copyDatabase("db_to_rename","db_renamed","localhost")
use db_to_rename
db.dropDatabase();

Also, try this method

The following shows you how to rename

> show dbs;
testing
games
movies

To rename you use the following syntax

db.copyDatabase("old db name","new db name")

Example:

db.copyDatabase('testing','newTesting')

Now you can safely delete the old db by the following way

use testing;

db.dropDatabase(); //Here the db **testing** is deleted successfully

Now just think what happens if you try renaming the new database name with an existing database name

Example:

db.copyDatabase('testing','movies'); 

So in this context, all the collections (tables) of testing will be copied to movies database.

ALERT: Just be careful while copying the database, if you don’t want to mess up the different collections under a single database.

10. How to fix error “sudo chown mongod:mongod /data/db“?

Answer:

You might have created the directory in the wrong place

/data/db means that it’s directly under the ‘/’ root directory, whereas you might have created ‘data/db’ (without the leading /) probably just inside another directory, such as the ‘/root’ homedirectory.

You need to create this directory as root

Either you need to use sudo , e.g. sudo mkdir -p /data/db

Or you need to do su - to become superuser, and then create the directory with mkdir -p /data/db

Note:

MongoDB also has an option where you can create the data directory in another location, but that’s generally not a good idea, because it just slightly complicates things such as DB recovery, because you always have to specify the db-path manually. It is not recommended to do that.

If the error message you’re getting is “Unable to create/open lock file: /data/db/mongod.lock errno:13 Permission denied”. The directory you created doesn’t seem to have the correct permissions and ownership -it needs to be writable by the user who runs the MongoDB process.

To see the permissions and ownership of the ‘/data/db/’ directory, do this: (this is what the permissions and ownership should look like)

$ ls -ld /data/db/
drwxr-xr-x 4 mongod mongod 4096 Oct 26 10:31 /data/db/

The left side ‘drwxr-xr-x’ shows the permissions for the User, Group, and Others. ‘mongod mongod’ shows who owns the directory, and which group that directory belongs to. Both are called ‘mongod’ in this case.

If your ‘/data/db’ directory doesn’t have the permissions and ownership above, do this:

First, check what user and group your mongo user have:

# grep mongo /etc/passwd
mongod:x:498:496:mongod:/var/lib/mongo:/bin/false

You should have an entry for mongod in /etc/passwd , as it’s a daemon.

sudo chmod 0755 /data/db
sudo chown -R 498:496 /data/db    # using the user-id , group-id

You can also use the user-name and group-name, as follows: (they can be found in /etc/passwd and /etc/group )

sudo chown -R mongod:mongod /data/db 

that should make it work.

Some people use this:

sudo chown -R `id -u` /data/db
sudo chmod -R go+w /data/db

or

sudo chown -R $USER /data/db 
sudo chmod -R go+w /data/db

The disadvantage is that $USER is an account that has a login shell. Daemons should ideally not have a shell for security reasons, that’s why you see /bin/false in the grep of the password file above.

Maybe also check out one of the tutorials you can find via Google: “UNIX for beginners”.

In Conclusion

This is the list for 10 most asked MongoDB questions. Hope you are clear about your query regarding MongoDB. If you haven’t found exactly what you have been looking for, please drop your comment. We will get in touch with you as soon as possible.

Leave a Reply

Your email address will not be published. Required fields are marked *