Blog Post‎ > ‎

Mongo: Snack Menu

posted Jun 21, 2015, 7:13 PM by Julian Zhu   [ updated Jun 21, 2015, 7:30 PM ]
Like Mongo? Lemon?

Here is my quick reference note ...


Mongo Command line tool

> mongo

 Command    Description
 > help
 
 > db.test.save({a:1})
 database save operation for db test.
 > db.test.find()
 database find operation for db test.
 > use db_name
 use this db db_name
 > show dbs
 show all databases
 > db
 show current db name
  


Java

MongoClient dbClient = new MongoClient("localhost", 27017);
MongoDatabase db = dbClient.getDatabase("db_name");
boolean auth = db.authenticate("myUserName", "myPassword");



Set<String> collections = db.getCollectionNames();
System.out.println(collections); // [datas, names, system.indexes, users]

DB db = mongo.getDB("db_name");
DBCollection col = db.getCollection("collection_name");



use DBCollection drop() method to drop a collection from the database.



import com.mongodb.BasicDBObjectBuilder;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.WriteResult;

BasicDBObjectBuilder docBuilder = BasicDBObjectBuilder.start();
docBuilder.append("_id", "1234");
docBuilder.append("name", "test_name");
docBuilder.append("role", "test_role");
docBuilder.append("isMember", true);
DBObject doc = docBuilder.get();

MongoClient mongo = new MongoClient("localhost", 27017);
DB db = mongo.getDB("db_name");

DBCollection col = db.getCollection("users");

//Create record
WriteResult result = col.insert(doc);
System.out.println(result.getUpsertedId());
System.out.println(result.getN());
System.out.println(result.isUpdateOfExisting());
System.out.println(result.getLastConcern());

//Read record
DBObject query = BasicDBObjectBuilder.start().add("_id", "1234").get();
DBCursor cursor = col.find(query);
while(cursor.hasNext()){
System.out.println(cursor.next());
}

//Update record
BasicDBObjectBuilder docBuilder = BasicDBObjectBuilder.start();
docBuilder.append("name", "test_name");
DBObject doc = docBuilder.get();

result = col.update(query, doc);
System.out.println(result.getUpsertedId());
System.out.println(result.getN());
System.out.println(result.isUpdateOfExisting());
System.out.println(result.getLastConcern());

//Delete record
result = col.remove(query);
System.out.println(result.getUpsertedId());
System.out.println(result.getN());
System.out.println(result.isUpdateOfExisting());
System.out.println(result.getLastConcern());

//Close connection
mongo.close();


Comments