mongodb-query-api

MongoDB Query API

The MongoDB Query API is the way you will interact with your data.

The MongoDB Query API can be used two ways:

  • CRUD Operations
  • Aggregation Pipelines

You can use the MongoDB Query API to perform:

  • Adhoc queries with mongosh, Compass, VS Code, or a MongoDB driver for the programming language you use.
  • Data transformations using aggregation pipelines.
  • Document join support to combine data from different collections.
  • Graph and geospatial queries.
  • Full-text search.
  • Indexing to improve MongoDB query performance.
  • Time series analysis.

Create Database using mongosh

After connecting to your database using mongosh, you can see which database you are using by typing db in your terminal.

C:\Users\default1>mongosh "mongodb+srv://cluster0.vdvjqwz.mongodb.net/" --apiVersion 1 --username mehzan07
Enter password: *********
Current Mongosh Log ID: 6540dbe472ee66043ea59d8c
Connecting to:          mongodb+srv://<credentials>@cluster0.vdvjqwz.mongodb.net/?appName=mongosh+1.10.6
Using MongoDB:          6.0.11 (API Version 1)
Using Mongosh:          1.10.6
mongosh 2.0.2 is available for download: https://www.mongodb.com/try/download/shell

For mongosh info see: https://docs.mongodb.com/mongodb-shell/

Atlas atlas-smbkyk-shard-0 [primary] test> db
test
Atlas atlas-smbkyk-shard-0 [primary] test>

If you have used the connection string provided from the MongoDB Atlas dashboard, you should be connected to the myFirstDatabase database.

sign in via https://www.mongodb.com/ then you have your Dashboard:

Show all databases

To see all available databases, in your terminal type show dbs.

Notice that myFirstDatabase is not listed. This is because the database is empty. An empty database is essentially non-existant.

Change or Create a Database

You can change or create a new database by typing use then the name of the database. Example, to create a DB: blog

>use blog
switched to db blog

We are now in the blog database.

Notes: In MongoDB, a database is not actually created until it gets content!

 

Create Collection using mongosh

There are 2 ways to create a collection.

Method 1

You can create a collection using the createCollection() database method.

Example:

db.createCollection("posts")
{ ok: 1 }
Atlas atlas-smbkyk-shard-0 [primary] blog>

Method 2

You can also create a collection during the insert process.

Example:

We are here assuming object is a valid JavaScript object containing post data:

db.posts.insertOne("object")
{
acknowledged: true,
insertedId: ObjectId("6540f336d7cbc92a793a0134")
}
Atlas atlas-smbkyk-shard-0 [primary] blog>

This will create the “posts” collection if it does not already exist.

Insert Documents

There are 2 methods to insert documents into a MongoDB database.

insertOne()

To insert a single document, use the insertOne() method.

This method inserts a single object into the database.

Note: When typing in the shell, after opening an object with curly braces “{” you can press enter to start a new line in the editor without executing the command. The command will execute when you press enter after closing the braces.

Example

db.posts.insertOne({
  title: "Post Title 1",
  body: "Body of post.",
  category: "News",
  likes: 1,
  tags: ["news", "events"],
  date: Date()
})

Note: If you try to insert documents into a collection that does not exist, MongoDB will create the collection automatically.

insertMany()

To insert multiple documents at once, use the insertMany() method.

This method inserts an array of objects into the database.

Example

db.posts.insertMany([  
  {
    title: "Post Title 2",
    body: "Body of post.",
    category: "Event",
    likes: 2,
    tags: ["news", "events"],
    date: Date()
  },
  {
    title: "Post Title 3",
    body: "Body of post.",
    category: "Technology",
    likes: 3,
    tags: ["news", "events"],
    date: Date()
  },
  {
    title: "Post Title 4",
    body: "Body of post.",
    category: "Event",
    likes: 4,
    tags: ["news", "events"],
    date: Date()
  }
])

Find Data

There are 2 methods to find and select data from a MongoDB collection, find() and findOne().

find()

To select data from a collection in MongoDB, we can use the find() method.

This method accepts a query object. If left empty, all documents will be returned.

Example

db.posts.find()

findOne()

To select only one document, we can use the findOne() method.

This method accepts a query object. If left empty, it will return the first document it finds.

Note: This method only returns the first match it finds.

Note: This method only returns the first match it finds.

Example

db.posts.findOne()

Querying Data

To query, or filter, data we can include a query in our find() or findOne() methods.

Example

db.posts.find( {category: "News"} ) 

Projection

Both find methods accept a second parameter called projection.

This parameter is an object that describes which fields to include in the results.

Note: This parameter is optional. If omitted, all fields will be included in the results.

Example

db.posts.find({}, {title: 1, date: 1})

This example will only display the title and date fields in the results.

Notice that the _id field is also included. This field is always included unless specifically excluded.

We use a 1 to include a field and 0 to exclude a field.

Example

This time, let’s exclude the _id field.

db.posts.find({}, {_id: 0, title: 1, date: 1})

Note: You cannot use both 0 and 1 in the same object. The only exception is the _id field. You should either specify the fields you would like to include or the fields you would like to exclude.

Let’s exclude the date category field. All other fields will be included in the results.

Example

db.posts.find({}, {category: 0})

We will get an error if we try to specify both 0 and 1 in the same object.

Example

db.posts.find({}, {title: 1, date: 0})

Update Document

To update an existing document we can use the updateOne() or updateMany() methods.

The first parameter is a query object to define which document or documents should be updated.

The second parameter is an object defining the updated data.


updateOne()

The updateOne() method will update the first document that is found matching the provided query.

Let’s see what the “like” count for the post with the title of “Post Title 1”:

Example

db.posts.updateOne( { title: "Post Title 1" }, { $set: { likes: 2 } } )

Check the document again and you’ll see that the “like” have been updated.

Insert if not found

If you would like to insert the document if it is not found, you can use the upsert option.

Example

Update the document, but if not found insert it:

db.posts.updateOne( 
  { title: "Post Title 5" }, 
  {
    $set: 
      {
        title: "Post Title 5",
        body: "Body of post.",
        category: "Event",
        likes: 5,
        tags: ["news", "events"],
        date: Date()
      }
  }, 
  { upsert: true }
)

updateMany()

The updateMany() method will update all documents that match the provided query.

Example

Update likes on all documents by 1. For this we will use the $inc (increment) operator:

db.posts.updateMany({}, { $inc: { likes: 1 } })

Now check the likes in all of the documents and you will see that they have all been incremented by 1.

Delete Documents

We can delete documents by using the methods deleteOne() or deleteMany().

These methods accept a query object. The matching documents will be deleted.

deleteOne()

The deleteOne() method will delete the first document that matches the query provided.

Example

db.posts.deleteOne({ title: "Post Title 5" })

deleteMany()

The deleteMany() method will delete all documents that match the query provided.

Example

db.posts.deleteMany({ category: "Technology" }) 

Conclusion

In this post i have described MongoDB, Query API, Create DB,  Create post (insert) query data (get ) Update data, and Delete data.

In my next post I will explore MongoDB Query Operators

This post is part of MongoDB-Step by step.

Back to home page

 

Leave a Reply

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