Monk Driver for MongoDB – How to Create/Insert Documents?

Want create site? Find Free WordPress Themes and plugins.

There are many ways to access MongoDB, and Mongoose is the most common one. However, Mongoose has one major disadvantage, i.e., predefined schemas. In a world where dynamicity is of crucial importance, the predefined schemas come as a major drawback.

Therefore, out of all the existing MongoDB drivers, I believe Monk is extremely efficient. Why?

  • It has a simple interface that is easy to comprehend
  • It has an excellent processing time
  • It does not require a schema structure
  • Easy to connect and configure
  • Easily interoperable with modules
  • Both global and collective level options can be set for queries

However, the problem is that there are not enough tutorials to educate people on how to use Monk in MongoDB. I’ve made a series that you can follow up on. In this blog, you will learn how to create/insert documents in MongoDB using the Monk driver.

To connect to MongoDB using Monk, just follow these simple  steps  :

Install Monk through NPM (Node Package Manager). Once you are done with the installation, you need to fire the below command and you are ready to use Monk.

const db = require('monk')('localhost/mydb')
const users = db.get('dbusers')
db.close()

We all know that CRUD (Create, Select, Update & Delete) is an important part of any database schema. In this series, I will start with the first part, i.e., Creation/Insertion.

  • To create/insert one document at a time.
    Here we will use the Insert () method. It is a simple method provided by MongoDB which generates a unique    id, with the name ‘_id’. Essentially, it is an auto generated hexadecimal string in MongoDB.

          Example:

db.collectionName.insert({fieldname1:value1,fieldname2:value2… fieldnameN:value N})
  • To create/insert more than one document at a time.
    There might be some cases where you might want to insert more than one document (in groups or batches).

                 i)  MongoDB allows multiple inserts inside a single query.

                      Example:

db.collectionName.insertMany([{document1},{document2},{document3},......{n}])

                ii) Use the $addToSet method to insert more than one document. 
Although this is a method used to update documents, it comes in handy, to insert multiple documents in a single query. You can fire the below-mentioned query for the same.

Example:

db.collectionName.update ({},{$addToSet:{value}},{upsert:true})

Please Note: upsert:true is used when you want to insert a unique document.

That’s all for insertion/creation! I will continue updating the blog with more queries. Stay tuned.
Upcoming blog on ‘Selection in MongoDB using Monk.

Did you find apk for android? You can find new Free Android Games and apps.

Tags

Related Posts

Leave A Comment