使用java操作MongoDB Demo
public class Demo { public static void main(String[] args) { Mongo conn = null; DB db = null; try { conn = new Mongo("localhost", 27017); db = conn.getDB( "test" ); } catch (UnknownHostException e) { e.printStackTrace(); } catch (MongoException e) { e.printStackTrace(); } /**获取所有collection**/ for (String s : db.getCollectionNames()) { System.out.println(s); } /**获取一个collection**/ DBCollection coll = db.getCollection("testCollection"); BasicDBObject doc = new BasicDBObject(); doc.put("name", "MongoDB"); doc.put("type", "database"); doc.put("count", 1); BasicDBObject info = new BasicDBObject(); info.put("x", 203); info.put("y", 102); doc.put("info", info); /**插入Document**/ coll.insert(doc); /**调试**/ DBObject myDoc = coll.findOne(); System.out.println(myDoc); /******************************************/ /**插入多个document**/ for (int i=0; i < 100; i++) { coll.insert(new BasicDBObject().append("i", i)); } /**计算有多少个document**/ System.out.println(coll.getCount()); /**使用DBCursor 类获取所有document**/ DBCursor cur = coll.find(); while(cur.hasNext()) { System.out.println(cur.next()); } /**带条件的查询**/ BasicDBObject query = new BasicDBObject(); query.put("i", 98); //查i的值为98的所有对象 cur = coll.find(query); while(cur.hasNext()) { System.out.println(cur.next()); } /**解析json格式的字符串**/ Object o = JSON.parse("{ \"name\" : \"MongoDB\", \"type\" : \"database\",\"count\" : 1, \"info\" : \"sdfsdf\"}"); BasicDBObject oo = (BasicDBObject)o; System.out.println(oo.get("name")); } }
相关推荐
lbyd0 2020-11-17
BigYellow 2020-11-16
sushuanglei 2020-11-12
我心似明月 2020-11-09
zhushenghan 2020-11-09
sunnnyduan 2020-10-16
不要皱眉 2020-10-14
xiaohai 2020-09-29
songxiugongwang 2020-09-22
萌亖 2020-09-17
LuckyLXG 2020-09-08
sdmzhu 2020-09-01
mkhhxxttxs 2020-09-16
xiaohai 2020-09-16
newcome 2020-09-09
jaylong 2020-08-19
大秦铁骑 2020-08-19
thatway 2020-08-19