Showing posts with label MongoDB. Show all posts
Showing posts with label MongoDB. Show all posts

Monday 9 September 2019

MongoDB update and delete records with examples

MongoDB update and delete records with examples




Question: How to Update Single Record? (Even Multiple Found)
db.players.update({"age":29},{$set:{number:1000}})
It will delete single record.
Output
WriteResult({"nMatched":1,"nUpserted":0,"nModified":1})



Question: How to update Update multiple Record? - 1 way
db.players.update({"age":29},{$set:{number:100}},{multi:true})
It will delete multiple record.
Output
WriteResult({
  "acknowledged": true,
  "matchedCount": 3,
  "modifiedCount": 3
})



Question: How to Update multiple Record? - 2 Way
db.players.updateMany({"age":29},{$set:{number:135}})
Output
WriteResult({
  "acknowledged": true,
  "matchedCount": 3,
  "modifiedCount": 3
})



Question: How to remove a Record(s)?
db.players.remove({"_id" : ObjectId("57ce95da8a12a77c41313adc")});
Will Delete all the record with matched condition.
Output
WriteResult({"nRemoved":1})



Question: How to remove a Record(s) with limit?
db.players.remove({"age":30},2);
It will deleted only 2 records.
Output
WriteResult({"nRemoved":2})



Sunday 8 September 2019

Mongodb index commands with examples

Mongodb index commands with examples

Create OR Use existing Database
use bank;



Create a new collection.
db.createCollection("users");



Add Records in collection.
db.users.insert([{"isActive":false,"balance":"$3,960.64","age":30,"eyeColor":"blue","name":"Dawn Keith","gender":"female","company":"COSMOSIS","email":"dawnkeith@cosmosis.com","phone":"+1 (839) 437-3421","address":"392 Clifford Place, Fontanelle, Arizona, 2687"},{"isActive":false,"balance":"$1,280.14","age":31,"eyeColor":"green","name":"Bettie Eaton","gender":"female","company":"COMTREK","email":"bettieeaton@comtrek.com","phone":"+1 (861) 460-2317","address":"203 Allen Avenue, Elrama, North Carolina, 4453"},{"isActive":true,"balance":"$2,042.37","age":38,"eyeColor":"green","name":"Margie Ayala","gender":"female","company":"VOIPA","email":"margieayala@voipa.com","phone":"+1 (941) 569-2231","address":"111 Schroeders Avenue, Suitland, Louisiana, 7042"},{"isActive":false,"balance":"$3,170.35","age":37,"eyeColor":"blue","name":"Baker Townsend","gender":"male","company":"EVIDENDS","email":"bakertownsend@evidends.com","phone":"+1 (808) 500-2793","address":"190 Just Court, Canoochee, Alabama, 325"}]);



Get all records
db.users.find().pretty();




Analyse the Query
db.users.find().explain("executionStats");



Add Index on collection
db.users.ensureIndex({"age":1});



Get all indexes on collection.
db.users.getIndexes();
Output
[
  {
    "v": 1,
    "key": {
      "_id": 1
    },
    "name": "_id_",
    "ns": "bank.users"
  },
  {
    "v": 1,
    "key": {
      "age": 1
    },
    "name": "age_1",
    "ns": "bank.users"
  }
]



Delete Index on collection.
db.users.dropIndex({"age":1});
Output
{
  "nIndexesWas": 2,
  "ok": 1
}



Drop all indexes.
db.users.dropIndexes();
Output
{
  "nIndexesWas": 1,
  "msg": "non-_id indexes dropped for collection",
  "ok": 1
}



Check Indexes, after droping an index.
db.users.getIndexes();
Output
[
  {
    "v": 1,
    "key": {
      "_id": 1
    },
    "name": "_id_",
    "ns": "bank.users"
  }
]



ReIndex the collecton.
db.users.reIndex()
Output
{
  "nIndexesWas": 1,
  "nIndexes": 1,
  "indexes": [
    {
      "key": {
        "_id": 1
      },
      "name": "_id_",
      "ns": "bank.users"
    }
  ],
  "ok": 1
}



Simple Aggregate Example
db.users.aggregate({$group:{_id:"$age",total:{$sum:1}}});
Output
{
  "_id": 37,
  "total": 1
}{
  "_id": 38,
  "total": 1
}{
  "_id": 31,
  "total": 1
}{
  "_id": 30,
  "total": 2
}



Average Aggregate Example
db.users.aggregate({$group:{_id:"$gender",avgAge:{$avg:"$age"}}});
Output
{
  "_id": "female",
  "avgAge": 32.25
}{
  "_id": "male",
  "avgAge": 37
}



Max Value in Aggregate
db.users.aggregate({$group:{_id:"$gender",richest:{$max:"$balance"}}});
Output
{
  "_id": "female",
  "richest": "$3,960.64"
}{
  "_id": "male",
  "richest": "$3,170.35"
}



Saturday 31 August 2019

MongoDB operators with examples

MongoDB operators with examples

Comparison Query Selectors

$eq  Equal to a specified value.
$gt  Greater than a specified value.
$gte  Greater than or equal to a specified value.
$lt  Less than a specified value.
$lte  Less than or equal to a specified value.
$ne  Not equal to a specified value.
$in  Matches any of the values specified in an array.
$nin  Matches none of the values specified in an array.

Example:
db.mycollectiontest.find('{"likes": {$gt:10}"likes"}'); 


Logical Query Selectors
$or  Joins query clauses with a logical OR Operator.
$and  Joins query clauses with a logical AND Operator.
$not  Inverts the effect of a query expression.
$nor  Joins query clauses with a logical NOR returns.

Example
db.mycollectiontest.find({"likes": {$gt:10}, $or: [{"by": "tutorials point"})


Element Query Selectors
$exists  Matches documents that have the specified field.
$type  Selects documents if a field is of the specified type.



Evalution Query Selector
$mod  Performs a modulo operation.
$regex  Specified regular expression.
$text  Performs text search.
$where  Matches documents that satisfy a JavaScript expression.



Array Query Selector
$all        Matches arrays that contain all elements specified in the query.
$elemMatch Selects documents if element in the array field matches all the specified $elemMatch conditions.
$size       Selects documents if the array field is a specified size.


Field Update Operators
$inc        Increments the value.
$mul        Multiplies the value.
$rename     Renames a field.
$setOnInsert Sets the value of a field if an update results in an insert of a document.
$set  Sets the value of a field in a document.
$unset  Removes the specified field from a document.
$min  Only updates the field if the specified value is less than the existing field value.
$max  Only updates the field if the specified value is greater than the existing field value.
$currentDate  Sets the value of a field to current date, either as a Date or a Timestamp.





Monday 19 August 2019

MongoDb PHP functions Questions and Answers

MongoDb PHP functions Questions and Answers

Question: How to connect to MongoDb with PHP?
$mongoObj = new MongoClient();



Question: How to select database?
$mongoDbObj = $mongoObj->mydb;



Question: How to create collection?
$collection = $mongoDbObj->createCollection("mycollectiontest");



Question: How to select collection?
$collection= $mongoDbObj->mycollectiontest;



Question: How to insert document in collection?
/* 1 document */
$document = array( 
      "title" => "MongoDB", 
      "description" => "MongoDB database", 
      "likes" => 100,
      "unlikes", 50
   );
   $collection->insert($document);
/* 2 document */
$document = array( 
      "title" => "MongoDB2", 
      "description" => "MongoDB database2", 
      "likes" => 1002,
      "unlikes", 502
   );
   $collection->insert($document); 



Question: How to list all documents?
   $cursor = $collection->find();
   foreach ($cursor as $document) {
      print_r($document);
   }

Output
Array
(
    [_id] => MongoId Object
        (
            [$id] => 57c3e73d9ba8827012000029
        )

    [title] => MongoDB
    [description] => MongoDB database
    [likes] => 100
    [0] => unlikes
    [1] => 50
)
Array
(
    [_id] => MongoId Object
        (
            [$id] => 57c3e7e79ba8821815000029
        )

    [title] => MongoDB2
    [description] => MongoDB database2
    [likes] => 1002
    [0] => unlikes
    [1] => 502
)
Array
(
    [_id] => MongoId Object
        (
            [$id] => 57c3e8fb9ba882181500002a
        )

    [title] => MongoDB2
    [description] => MongoDB database2
    [likes] => 1002
    [0] => unlikes
    [1] => 502
)



Question: How to list all documents (2nd way)?
 $cursor = $mongoObj->mydb->{'mycollectiontest'}->find();
/*$mongoObj is clinet, mydb is database, mydb is collections*/
   foreach ($cursor as $document) {
      print_r($document);
   }



Question: How to list all documents (3rd way)?
$query = array('title' => 'MongoDB');
$cursor = $collection->find($query);
   foreach ($cursor as $document) {
      print_r($document);
   }



Question: How to delete a document?
 $collection->remove(array("title"=>"MongoDB2"));



Question: How to update a document?
  $collection->update(array("title"=>"MongoDB"), 
 array('$set'=>array("description"=>"This is updated description")));



Sunday 23 June 2019

Mongodb Data Model Design - Embedded data model & Reference data model

Mongodb Data Model Design - Embedded data model & Reference  data model

Question: What is Data Model Design?
Data modeling is first step in database design and object-oriented programming as the designers. It start from conceptual model to logical model to physical schema.


Question: What are different type of Data Model Design?
  1. Embedded Data Models
  2. Reference Data Models



Question: What is Embedded Data Model?
In Embedded Data Model, we store all releated in single document.
For example:
there is a user with name of salman and he has multiple address in different countries.
In this Embedded model, we store the address along with his details. means address and user details in single document.


Question: Give example of embedded Data Model?
One user 'Salman" have multiple address (2 address).
{
  name: 'Salman',
  ssn: '123-456-7890',
  addresses: [
    {
      street: '123 Sesame St',
      city: 'jaipur',
      cc: 'IN'
    },
    {
      street: '123 Avenue Q',
      city: 'New York',
      cc: 'USA'
    }
  ]
}



Question: Where embedded Data Model are good to used?
  1. Data that does not change regularly
  2. Document that grow by a small amount
  3. Data that you'll often need to perform ascending query to fetch
  4. Fast reading speed



Question: What is Normalized Data Models OR Reference Data Model?
In Normalized Data model, we store the user information in multiple collections.
For example,
Single user have multiple address.
Store the user details in user collections.
Store the user address in address collections.
in address collection, we set the reference to user collection.


Question: Give example of Normalized Data Models OR Reference Data Model?
One user 'Salman" have multiple address (2 address).
User collection
{
  id: 100
  name: 'Salman',
  ssn: '123-456-7890',
  
}

User's address collection
 {
      street: '123 Sesame St',
      city: 'jaipur',
      cc: 'IN',
      user_id:100
    }
 {
      street: '123 Avenue Q',
      city: 'New York',
      cc: 'USA',
     user_id:100
}



Question: Where Reference Data Model are good to used?
  1. Large sub documents
  2. When immediate consistency is necessary
  3. Document grow with a large amount
  4. Fast write speed