Copy/Clone a Database in MongoDB

In earlier versions of MongoDB, you could use the copyDB command or its helper method, db.copyDatabase() to copy a database.

MongoDB has since deprecated these. Also, starting in version 4.2, MongoDB has removed the copydb command, and therefore also the db.copyDatabase() method, which means that you can’t use them even if you wanted to if you’re using MongoDB 4.2 or later.

Fortunately, there’s another way to copy a MongoDB database.

Continue reading →

Copy/Clone a Collection in MongoDB

In earlier versions of MongoDB, you could use the db.collection.copyTo() method to copy a collection.

MongoDB has since deprecated that method. Also, starting in version 4.2, MongoDB has removed the eval command. Given db.collection.copyTo() wraps eval, this means that you can’t use either of them if you’re using MongoDB 4.2 or later.

Fortunately, there’s another way to copy a MongoDB collection.

Continue reading →

Back Up a MongoDB Database using mongodump

There are several ways to back up a database in MongoDB. One quick way to back up a database is to use the mongodump tool.

mongodump reads data from a MongoDB database and creates high fidelity BSON files which the mongorestore utitlity can use to restore a MongoDB database.

With mongodump, you can back up a collection, a database, or all databases.

Continue reading →

MongoDB distinct()

In MongoDB, the db.collection.distinct() method finds the distinct values for a specified field across a single collection or view and returns the results in an array.

Distinct values are those with redundant duplicates removed. Distinct values are unique values. For example, if you have 2 or 3 documents with the same value, the distinct command will return just one value.

db.collection.distinct() is a shell wrapper method for the distinct command.

Continue reading →

MongoDB $sortByCount Aggregation Operator

In MongoDB the $sortByCount aggregation pipeline stage groups incoming documents based on the value of a specified expression, then computes the count of documents in each distinct group.

Each group is output in its own document, which consists of two fields:

  • an _id field containing the distinct grouping value, and
  • count field containing the number of documents belonging to that grouping.

The documents are sorted by count in descending order.

Continue reading →