Mongodb Study Notes
Summary of Mongodb study notes over the past few days
/*** Get login client * @ author xuyw * @ email xyw10000@163.com * @ param host * @ param port * @ return */public static login client getlogin client (String host, int... port) {export client expose client = null; int portlen = 0; try {if (port! = Null) portlen = port. length; switch (portlen) {case 0: if (host! = Null &&! "". Equals (host) {// method 2 (specified ip): specify client = new specify client (host );} else {// directly connect to a single mongodb server mongoClient = new MongoClient ();} break; case 1: // method 2 (specified ip address and port): mongoClient = new MongoClient (host, port [0]); break; default: // method 3: connect to the mongodb server cluster (the master server will be automatically discovered) List list = new ArrayList (); string [] hostip = host. split (","); for (int I = 0; I <portlen; I ++) {ServerAddress saddress = new ServerAddress (hostip [I], port [I]); list. add (saddress) ;}expose client = new expose client (list); break ;}} catch (UnknownHostException e) {e. printStackTrace ();} return response client ;} '/*** get Db ** @ param dbname * @ param host * @ param port * @ return */public static DB getDB (String dbname, String host, int... port) {response client = getresponse client (host, port); DB db = Response client. getDB (dbname); return db ;}
Login Client Login client = MongoDbUtil. getlogin client ("192.168.1.101 ",
27017 );
// Query all databases
For (String name: Your client. getDatabaseNames ()){
System. out. println ("databaseName:" + name );
}
// Obtain the specified database
DB db = Response client. getDB ("xuywdb ");
// Query the names of all clustering sets similar to those in oracle
Set colls = db. getCollectionNames ();
for (String s : colls) { System.out.println(s); }
"
// Add two new records
Public void inserUser (DBCollection t_user ){
DBObject user = new BasicDBObject ();
User. put ("username", "James ");
User. put ("userage", 18 );
User. put ("usersex", "male ");
DBObject user2 = new BasicDBObject ();
User2.put ("username", "Xiaohong ");
User2.put ("userage", 19 );
User2.put ("usersex", "female ");
T_user.insert (user );
T_user.insert (user2 );
}
// Query all returns a cursor DBCollection t_user = db. getCollection ("t_user"); DBCursor cursor = t_user.find (); while (cursor. hasNext () {System. out. println (cursor. next ());}
Result output
{"_ Id": {"$ oid": "5550bf41d975cf177eab8d1f"}, "username": "zhangsan", "userage": 18, "usersex ": "male" }{ "_ id": {"$ oid": "5550bf41d975cf177eab8d20"}, "username": "Xiaohong", "userage": 19, "usersex ": "female "}
Json operation DBObject to jsonJSON. serialize (dBObject) json to DBObject JSON. parse ("{\" name \ ": \" xuyw \ ", \" age \ ": 23 }")