CRUD Operation in Mongo-cxx

What is CRUD operation ?

  1. Basically this term use in the database (like SQL,Mongo etc).

2. In Database we generally perform four operation :

C – Create : It will be perform create database by Inserting data .

R – Read : It will be perform Read operation of database.

U – Update : It will be perform Update Database by using unique key.

D – Delete : It will be perform Delete operation in Database using unique key.

3 . Example

#include <iostream>
#include <bits/stdc++.h> 

#include <bsoncxx/builder/stream/document.hpp>
#include <bsoncxx/json.hpp>
#include <mongocxx/client.hpp>
#include <mongocxx/instance.hpp>
#include <cstdint>
#include <mongocxx/stdx.hpp>
#include <mongocxx/uri.hpp>

using bsoncxx::builder::stream::close_array;
using bsoncxx::builder::stream::close_document;
using bsoncxx::builder::stream::document;
using bsoncxx::builder::stream::finalize;
using bsoncxx::builder::stream::open_array;
using bsoncxx::builder::stream::open_document;
using bsoncxx::builder::basic::kvp;
using bsoncxx::builder::basic::make_document;
using bsoncxx::builder::basic::make_array;
using namespace std; 
  
int
main ()
{
    
  
   int n;
   int oid;
   char Firstname[15];
   char Lastname[15];
   char Company[15];
	
     mongocxx::instance instance{}; 
    mongocxx::uri uri("mongodb://localhost:27017");
    mongocxx::client client(uri);
    
	 	  
	 std::cout <<"1. INSERT\n";
	 std::cout <<"2. DELETE\n";
	 std::cout <<"3. SEARCH\n";
	 std::cout <<"4. UPDATE\n";
	 std::cout <<"Chosse No.\n";
	  std::cin >>n;
	  mongocxx::database db = client["TCS"];
	  mongocxx::collection coll = db["Employee"];
       auto builder = bsoncxx::builder::stream::document{};
       bsoncxx::document::value doc_value;
      
switch (n)
      {
  case 1:
     cout <<" ID Firstname Lastname Company";
     cin >>oid >>Firstname >>Lastname >>Company;
	  bsoncxx::document::value restaurant_doc = make_document(bsoncxx::document::value
 doc_value = make_document( kvp("id", oid) ,
  kvp("Firstname",Firstname),
  kvp("Lastname",Lastname),
  kvp("Company" ,Company)));
   auto res = coll.insert_one(std::move(doc_value));
	 break;  
   case 2:
      cout <<" ID ";
      cin >>oid;
     coll.delete_one(make_document(kvp("ID", oid)));
	 break;
  case 3:
       cout <<" Enter Firstname";
      cin >>Firstname;
      auto cursor = coll.find(make_document(kvp("Firstname", Firstname)));
      for (auto&amp;&amp; doc : cursor) 
        {
            std::cout << bsoncxx::to_json(doc) << std::endl;
        }
 	
	 break;   

  case 4:

    cout <<" Enter id";
    cin >>oid;
   cout<<"Company Name";
   cin>> Company;
   coll.update_one(
            make_document(kvp("id", oid)),
            make_document(kvp("$set", make_document(kvp("Company", Company)))));

  break; 
	 
  default:
    break; 
 }
	
   

      return 0;
  }

1 comment

Leave a Reply

%d bloggers like this: