Summarize the next few days MongoDB study notes
/** * Get mongoclient * @author xuyw * @email [email protected] * @param Ho St * @param port * @return */ Public StaticMongoclientgetmongoclient(String host,int... port) {Mongoclient mongoclient =NULL;intPortlen =0;Try{if(Port! =NULL) Portlen = Port.length;Switch(Portlen) { Case 0:if(Host! =NULL&&!"". Equals (host)) {//Mode two (Specify IP):Mongoclient =NewMongoclient (host); }Else{//Direct connection to a single MongoDB serverMongoclient =NewMongoclient (); } Break; Case 1://Mode two (specify IP, port):Mongoclient =NewMongoclient (Host, port[0]); Break;default://Mode three: Connect to a MONGODB server cluster (will automatically discover the primary server)List List =NewArrayList (); string[] HostIP = Host.split (","); for(inti =0; i < Portlen; i++) {ServerAddress saddress =NewServerAddress (Hostip[i], port[i]); List.add (saddress); } mongoclient =NewMongoclient (list); Break; } }Catch(Unknownhostexception e) {E.printstacktrace (); }returnMongoclient; }``/** * Get DB * * @param dbname * @param host * @param port * @re Turn * * Public StaticDbGetdb(String dbname, String host,int... port) {mongoclient mongoclient = getmongoclient (host, Port); DB db = Mongoclient.getdb (dbname);returndb }
Mongoclient mongoclient = mongodbutil.getmongoclient ("192.168.1.101",
27017);
Query all the database
For (String name:mongoClient.getDatabaseNames ()) {
System.out.println ("DatabaseName:" + name);
}
Gets the specified database
DB db = Mongoclient.getdb ("xuywdb");
Querying all clustered collections similar to the name of a table in Oracle
Set colls = Db.getcollectionnames ();
for (String s : colls) { System.out.println(s); }
“
2 new Records added
public void Inseruser (Dbcollection t_user) {
DBObject user = new Basicdbobject ();
User.put ("username", "Zhang San");
User.put ("Userage", 18);
User.put ("Usersex", "male");
DBObject user2 = new Basicdbobject ();
User2.put ("username", "Little Red");
User2.put ("Userage", 19);
User2.put ("Usersex", "female");
T_user.insert (user);
T_user.insert (User2);
}
//查询所有返回一个游标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" : "Zhang San" , "Userage" : -, "Usersex" :"Male"}{ "_id" :{"$oid": "5550BF41D975CF177EAB8D20"}, "username" : "Little Red" , "Userage" : +, "Usersex" :"female"}
json 操作DBObject 转jsonJSON.serialize(dBObject )json转DBObject JSON.parse("{\"name\"\"xuyw\"\"age\" : 23}")
MongoDB Learning Notes