MongoDB shell examples

I would like to cover a couple of useful queries to be run in a MongoDB shell. They come from my daily hands-on experience and these are the queries that might be useful for someone who starts with MongoDB. However I am not saying this is the ultimate set of best examples;) someone else might find better examples for their needs.

It is good to start with a database client first. I use Robomongo, which works just fine and is free. There is only one thing to be aware of, based on my experience: If you run a long running query from Robomongo, it will just return after some timeout and the query (if updating) will not finish. Maybe there is some way to increase the timeout, however it is safer to run long running scripts using Mongo command prompt.

Ok, now let’s get started with the examples!

Find based on ID

The simplest example first:

You can use the same query and change the _id to any other field in your document. Please note the function ObjectId() which converts the ID from string. Search based on the string representation of the ID returns empty result.

AND or OR the filters:

Replace the $and operator with $or if you need to OR the filters. You can also chain AND’s and OR’s as the nested values in the array of these operators.

Find based on nested document

If you have sub document nested within the main document such as the details field below:

And now let’s say you wish to query based on the nested field details.category. Just wrap the field name in the filter with quotes, without them you get an error:

Date-based search

You can search based on the dates in the ISO format (ISO8601):

Where you can use the function ISODate to convert the string into date object.

Use operators $gt, $lt, $gte, $lte, $eq, $ne – greater then, lower then, greater then or equal, lower than or equal, equal, not equal, resp. as needed.

Nested arrays

In many situations you need to find document which has at least one item in a nested array, something like “where yourDocument.nestedArray.length > 0”. The easiest way (and probably fastest) to achieve this is to filter the documents where array item with index 0 exists:

As a side note: I think there is no way to create index on the number of items in the array if you have many of the documents and would like to add index for this metrics.

Aggregate for “GROUP BY”

In SQL Server you would use GROUP BY quite often for group the rows based on one or multiple columns, especially for reporting. You can achieve similar functionality via aggregation framework:


A couple of notes on the example above:

  • _id on the line 3 really needs to be named “_id”
  • line 4 defines the fields we want to group by, more can be added in JSON format – after comma
  • productIds on line 6 will contain ID’s of all documents within each group
  • count on line 7 adds count so that we could filter only the records with count > 1 on line 10


$set and $unset within update

You can update the values of documents using $set operator. Use command update to update a single document or updateMany to iterate over all matching documents. The first parameter is the filter –  {_id: ObjectId("58bd8a64ce3b6f0db8b94e9b")}

The second one is the update where each field to be updated in the target document needs to be specified:


Please note the NumberInt(0), which adds “0” as integer. Otherwise a decimal 0.0 would be added.

If you want to remove a field from objects entirely you can use the $unset command. The value of the field doe not matter in the following example:


Send a Comment

Your email address will not be published.