MongoDB - Other

How to use MongoDB with query

MongoDB database query, All mongoDB commands, MongoDB Query Operators, MongoDB Schema and Schema Validation

What is MongoDB, How to use MongoDB, Learn MongoDB with query and oprators

MongoDB

MongoDB is a object oriented database or document database and can be installed locally or hosted in the cloud.

MongoDB is object oriented database its store data in object format you can say MongoDB is a documented database, MongoDB store data in JSON format call BSON.

MongoDB is store record as a document, it is data structure component of key value pairs. This is store data in a key value pair. In mongoDB we can add any new kay value like object and insert, update, delete.

What is MongoDB Document

MongoDB database record are called documents like in SQL row in a table all row are called a document. In a document the field value maybe string, number, boolenes, array or a nested document.


Document Databases vs SQL

Document database is a non-relational database but SQL databases are considered relational databases. SQL store data in separate tables, and when we get data from sql it is queried from multiple tables to join the data back together.

MongoDB is a document database this is a non-relational database. We can store relational data in document databases. This is store data in a documented form with nested document or can say data object with key value pair.

MongoDB stores data in flexible documents. This makes reading your data very fast.

In MongoDB collections are Like SQL Table.

In MongoDB collections document are Like SQL Table Row.

A- MongoDB Database Commands :

1. View all databases

show dbs

2. Create a new or change databases 

Remember – Database until not connect till there are a collection

use user

Note- ‘user’ is database name

3. View current Database

db

4. Delete Database 

db.dropDatabase()

Note- Before delete database be insure you are in correct database

B- MongoDB Collections Commands :

1. Show Collections

show collections

2. Create a new collection named ‘subjects’

db.createCollection("subjects")

Note- db.subjects.insertOne(object)

This command also create a new collections if collection is not exist

4. Drop a collection named ‘subjects’

db.subjects.drop()

C – MongoDB Row OR Document Commands

1. Show all Rows OR Document in a Collection 

db.subjects.find()

2. Show all Rows OR Document in a Collection (Prettified)

db.subjects.find().pretty()

3. Find the first row matching the object

db.subjects.findOne({name: 'xyz'})

4. Insert One Row in Collections

db.subjects.insertOne({
  name: "math",
  code: "MTH",
  category: "science",
  userId:"12334455"
  date: Date()
})

Note- insertOne will insert only one document in a collections

5. Insert many Rows in Collections

db.subjects.insertMany([{
  name: "math",
  code: "MTH",
  category: "science",
  userId:"12334455"
  date: Date()
},
{
  name: "EVS",
  code: "EVS",
  category: "science",
  userId:"12334455"
  date: Date()
},
{
  name: "English",
  code: "ENG",
  category: "science",
  userId:"12334455"
  date: Date()
}])

Note- insertMany will insert many document or a array of document in a collections

6. Find in a MongoDb Collections

db.subjects.find()
db.subjects.findOne()

Note- There are two methods to find data in collection

1. find() – This will return all documents from collections

2. findOne()- This will return a single documents from collections

7. Limit the number of rows in find

db.subjects.find().limit(10)

8. Count the number of rows in the find

db.subjects.find().count()

9. Search or filter data in a MongoDb Collections

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

db.subjects.find( {category: "science"} )
db.subjects.findOne( {category: "science"} )

Note – Both find methods accept two parameter first is query object like {category: “science”} and second parameter called projection like {category: 1} or {category: 0} both parameter are optional

projection parameter is describes which fields to include in the results.

db.subjects.find({}, {name: 1, date: 1})
db.subjects.find({}, {_id: 1, name: 1, date: 0})

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

10. Update a row or document in a collections

db.subjects.updateOne({name: 'xyz'},
{$set: {'name': 'abc',
    'category': 'science',
    "userId":"12334455",
   "date": Date()
}}, {upsert: true})

This will update the collection where name = “xyz” with new object in set. updateOne take three parameter

First query like which document want to update

Second is new document which is pass with $set: object

Third is upsert this is true/False and a optional. If upsert: true then if record not found the insert a new record in collection

11. Mongodb Increment Operator

db.subjects.update({name: 'xyz'},
{$inc:{
    like: 2
}})

12. Mongodb Rename Document key

db.subjects.update({name: 'xyz'},
{$rename:{
    date: 'date_from'
}})

13. Delete Documents 

db.subjects.remove({name: 'xyz'})
db.posts.deleteOne({name: 'xyz' })
db.posts.deleteMany({ name: 'xyz' })

MongoDB All Query Operators

The following operators can be used to update fields:

  • $currentDate: Sets the field value to the current date
  • $inc: Increments the field value
  • $rename: Renames the field
  • $set: Sets the value of a field
  • $unset: Removes the field from the document

The following operators assist with updating arrays.

  • $addToSet: Adds distinct elements to an array
  • $pop: Removes the first or last element of an array
  • $pull: Removes all elements from an array that match the query
  • $push: Adds an element to an array

Visited 8 times, 1 visit(s) today

Leave a Reply

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