Posts

Showing posts from September, 2018

MongoDB code for Mapreduce,Aggregation and Index

[student@localhost ~]$ su Password: su: Authentication failure [student@localhost ~]$ su Password: [root@localhost student]# systemctl start mongod [root@localhost student]# ./mongo bash: ./mongo: No such file or directory [root@localhost student]# mongo MongoDB shell version: 2.4.6 connecting to: test > use spp switched to db spp > db.createCollection("fruits"); { "ok" : 1 } > db.fruits.insert({"name":"Apple","cost":200}) > db.fruits.insert({"name":"Apple","cost":200}) > db.fruits.insert({"name":"Apple","cost":300}) > db.fruits.mapReduce(function(){emit(this.name,this.price);}function(key,values){return Array.sum(values)},{out:"MapReduce_F"}).find(); Thu Jan  1 14:51:33.905 SyntaxError: Unexpected token function > db.fruits.mapReduce(function(){emit(this.name,this.cost);}function(key,values){return Array.sum(values)},{out:&qu

Java MongoDB Connectivity -code snippet for Insert,Update,Search,Delete operations

Insert Save a document (data) into a collection (table) named “user”. DBCollection table = db . getCollection ( "user" ) ; BasicDBObject document = new BasicDBObject ( ) ; document . put ( "name" , "mkyong" ) ; document . put ( "age" , 30 ) ; document . put ( "createdDate" , new Date ( ) ) ; table . insert ( document ) ;      Update Update a document where “name=mkyong”. DBCollection table = db . getCollection ( "user" ) ; BasicDBObject query = new BasicDBObject ( ) ; query . put ( "name" , "mkyong" ) ; BasicDBObject newDocument = new BasicDBObject ( ) ; newDocument . put ( "name" , "mkyong-updated" ) ; BasicDBObject updateObj = new BasicDBObject ( ) ; updateObj . put ( "$set" , newDocument ) ; table . update ( query , updateObj ) ; Search Find document where “name=mkyong”, and display it with DBCursor DBCol

Java MongoDB connectivity Code

package mongoconn; ////import com.mongodb.client.MongoDatabase; import java.net.UnknownHostException; import java.sql.Date; import com.mongodb.BasicDBObject; import com.mongodb.MongoClient; import com.mongodb.DB; import com.mongodb.DBCollection; //import com.mongodb.MongoCredential;  public class myconn{       public static void main( String args[] ) throws UnknownHostException {              // Creating a Mongo client       MongoClient mongo = new MongoClient("localhost" , 27017 );          System.out.println("Connected to the database successfully");                DB db = mongo.getDB("SP");       DBCollection table = db.getCollection("user");                BasicDBObject document = new BasicDBObject();       document.put("name", "mkyong");       document.put("age", 30);       document.put("createdDate", new Date(0));       table.insert(document);    } }