MongoDb – Tips

MongoDB Data Types

Object

This data type stores embedded documents. When a document contains another document in the form of key-value pair then such type of document is known as an embedded document.

ObjectId

The ObjectId data type stores the document’s ID. ObjectId is small, likely unique, fast to generate, and ordered. The size of ObjectId is 12 bytes. These 12 bytes are divided into the following 4 parts.

Part Name Size(Bytes)
Time Stamp 4
Machine Id 3
Process Id 2
Counter 3

MongoDB uses an _id field for each document to uniquely identify them. This _id field s a primary something. It can’t be a duplicate. Data is stored in hexadecimal format in the _id field.

Date

This data type stores the current date or time in UNIX time format. MongoDB provides various methods to return the date, either as a string or as a Date object.

Date Method Description
Date() returns the current date as a string.
new Date() returns a Date object using the ISODate() wrapper.
ISODate() returns a Date object using the ISODate() wrapper.

We can specify your own date time by creating an object of Date and passing a day, month, and year into it. Date objects are stored as a 64-bit integer representing the number of milliseconds.

Timestamp
The Timestamp data type stores a timestamp. This can be useful for recording when a document has been modified or added. Timestamp values are a 64-bit value.
1. The first 32 bits are a time_t value (seconds since the Unix epoch)
2. The second 32 bits are an incrementing ordinal for operations within a given second.
Let’s see an example.

Example 1 :

In the preceding example, we can see that the starting value of the Timestamp is (0,0). After the insertion operation, the value of the timestamp is (1438791098,1). The first value of the timestamp is the current timestamp and the second value is the order of operation.

Example 2 :
MongoDB stores the current timestamp in ObjectId but we can retrieve this timestamp using the getTimestamp() method.

First, we insert a document into the collection, then we check the value of the Timestamp.

Now, we update a record and once again check the value of the Timestamp.

MongoDB: how to filter by multiple fields

How do I filter a MongoDB collection by multiple fields?

To retrieve all the customers in our collection that are from Germany, and are VIP we will run this command:

db.customers.find({
  "VIP": true,
  "Country": "Germany"
})

SQL equivalent:

SELECT * FROM customers WHERE VIP IS true AND Country = "Germany"

In MongoDB we filter by mutiple fields by separating the different fields we want to use as a filter by comas. There is an $and operator, but in this simple scenario we can leave it implicit. We will use the $and operator explicitly when we use it more complex queries mixing different conditions – as we will see in the next examples to come.

How to make a MongoDB query with an OR condition?

If we want to retrieve all the customer that come from Germany or France we will use this command:

db.customers.find({
  $or: [
    {
      Country: "Germany"
    },
    {
      Country: "France"
    }
  ]
})

SQL equivalent:

SELECT * FROM customers
WHERE (Country = "Germany" OR Country = "France")

How do I combine ANDs and ORs in MongoDB querys?

Now let’s imagine we want to find all the VIP customers that come from France or from Germany:

db.customers.find({
  $and: [
    {
      $or: [
        {
          "Country": "Germany"
        },
        {
          "Country": "France"
        }
      ]
    },
    {
      VIP: true
    }
  ]
})

SQL equivalent:

SELECT * FROM customers
WHERE VIP is true AND (Country = "Germany" OR Country = "France")

As we said earlier in this post, here we see an example of the usage of the $and operator, used in combination with the $or operator.

What about finding all the objects that do not match a property?

Or in other words who do I find all the objects in a collection whose property x does not equal a certain value? Well, for that we need to use the $ne -not equal- operator.

db.customers.find({
  Country: {
    $ne: "Germany"
  }
})

SQL equivalent:

SELECT * FROM customers
WHERE Country  "Germany"

Since we have already learned how to use AND and OR operator we can write more complex filters, for example we can query the collection for all the customers that do not come from Germany, and that are not VIP:

db.customers.find({
  $and: [
    {
      Country: {
        $ne: "Germany"
      }
    },
    {
      VIP: {
        $ne: true
      }
    }
  ]
})

SQL equivalent:

SELECT * FROM customers
WHERE Country "Germany" AND VIP is NOT True

How do I return only unique values in a MongoDB query?

As SQL MongoDB has a distinct feature that allows to ignore duplicated values. Let’s take our customers collection, and let’s imagine we want to find all the countries where we have customers younger than 30. We could try this query:

db.customers.find({
  Country: {
    $ne: "Germany"
  }
})

But since a country is bound to have multiple customers younger than 30 we would get an unnecessarily long list with repeated countries. So it is time to use the distinct function:

db.customers.distinct("Country",{
  age: {
    $lt: 30
  }
})

SQL equivalent:

SELECT distinct country FROM customers
WHERE age < 30

How to use comparison operators in MongoDB?

We have already seen some comparison operators: $ne – not equal-, and $lt – less than-. For sake of completeness let´s list the other operators of comparison as they are in MongoDB:

  • $eq equal (=).
  • $gt greater than >.
  • $gte greater or equal than (>=).
  • $in in (in).
  • $lt less than (<).
  • $lte less or equal than (<=).
  • $ne not equal ().
  • $nin not in (not in )

Let´s take the previous example about listing customers that came from Germany OR France, and let´s modify it to list all the customers whose country belongst to a given list:

db.customers.find({ "Country": { $in: ["Germany","France"] } })

SQL equivalent:

SELECT * FROM customers
WHERE Country IN ("Germany","France")

how to filter a field containing a string

In SQL we commonly use the LIKE function to compare strings. LIKE allow us to check if 2 strings are equal:

SELECT * FROM names n where n.name LIKE 'James Smith'

starting with ‘James’ - name LIKE 'James%'
ending with ‘Smith’ - n.name LIKE '%Smith'
contains a ‘a’ in any position - n.name LIKE '%a%'

SQL LIKE querys for MongoDB

In MongoDB we can query string fields quite easily using regular expressions. As an example let´s imagine we got a MongoDB collection of movies that has the following fields: title, plot, and director.
1. Now I am going to get a list of movies of my favourite director. I will filter by the director field, and get all the documents that end with ‘Spielberg’:

db.getCollection("movies").find({'director':/Spielberg$/ })

2. To make the query case insensitive we have to add an i like this:

db.getCollection("movies").find({'director':/Spielberg$/i })

3. Lets make a query to look for all the movies whose title starts with ‘Indiana Jones’, and I will also make my query case insensitive:

db.getCollection("movies").find({'title':/^indiana jones/i })

4. I need to search for those items that contain the word ‘Comedy’ in the genre field at any position …

db.getCollection("movies").find({'genre':/Comedy/})

5. To finish here it is an example of a query to search all the values that start with a given string, and finish with another given string:

db.getCollection("books").find({'title':/^john.*tolkien$/i })

how to search inside an array

Reference

OnlineMongoDBShell
Analyzing Bike Shareing DB
Developer Blog

Leave a Reply

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