Beginning MongoDB

MongoDB is a weird little database but seems really popular and works nicely with low overhead Javascript applications.

This article highlights a few key pointers when working with MongoDB

Difference mongodb-org versus mongodb packages

Be careful when installing MongoDB! There is an official version, called MongoDB-ORG and another one, which isn’t maintained by MongoDB-ORG. If you install the one with your Ubuntu package manager, you might end up with the wrong version. If you then install the proper one from MongoDB-ORG, you might not get it working.

For me this was a clue:

sudo apt-get install -y mongodb-org

The following packages have unmet dependencies:
mongodb-org : Depends: mongodb-org-database but it is not going to be installed

When I changed to Focal’s packages it was too late. Constant Core Dumps. Eventually I figured out I have the wrong version but nothing I did, including reading a ton of Stack articles about apt purge mongo* and permissions, couldn’t fix version 5 for me. Thankfully I found a way of installing 4.x and this worked.

Inserting Data

Here is a simple example from a Laravel MongoDB tutorial:

"title":"First Blog Post",
"body" :"Lorem Ipsum, etc.",
"slug" :"first-blog-post"

Here is another more complex example from the MongoDB website:

  name: { first: 'Alan', last: 'Turing' },
  birth: new Date('Jun 23, 1912'),
  death: new Date('Jun 07, 1954'),
  contribs: [ 'Turing machine', 'Turing test', 'Turingery' ],
  views : Long(1250000)

Retrieving Data

Mongo has a few tools to query but it appears there is one called ‘mongo’. Lol.

Here is a quick transcript how we retrieved some data (bold indicates commands):

> <strong>show databases</strong>
admin     0.000GB
config    0.000GB
local     0.000GB
myappdb   0.000GB
tyntec    0.000GB
whatsapp  0.000GB
> <strong>use tyntec</strong>
switched to db tyntec
> <strong>show tables</strong>
> <strong>db.contacts.find()</strong>
{ "_id" : ObjectId("xxx"), "phone" : "yyy", "name" : "Vander Host", "thread_ts" : "no thread assigned", "__v" : 0 }

Duplicate key error index

As a newbie this will be one of your first pains. You can’t insert data if the key is specific as unique.

Here’s an example. It’s a Tyntec contacts model, but the system failed because the thread is reset and then it becomes null, which can be a duplicate index. So we had to comment it out:

const ContactSchema = new mongoose.Schema({

   phone: {

   name: {

   thread_ts: {
      // unique: true,


Using with Laravel

One gotcha with Laravel, is you are extending a new ‘Model’, see below:

namespace App\Models;

use Jenssegers\Mongodb\Eloquent\Model;

class Post extends Model
   protected $connection = 'mongodb';

Passwordless Connection Info

If you don’t have authenticated MongoDB, this is your DSN:

'dsn' => env('DB_URI', 'mongodb://')

More Information

Share this article

Leave a Reply

Your email address will not be published.

Scroll to Top