package mongod; import java.util.List; import java.util.ArrayList; import org.bson.types.*; import com.mongodb.*; public class mongo { // DBObject o = new BasicDBObject(); public static void main(String[] args) { // TODO Auto-generated method stub MongoClient mo = new MongoClient("127.0.0.1",27017); DB db = mo.getDB("wtdd"); DBCollection col = db.getCollection("wtd"); /* 实现增加集合 db.createCollection("wtddd!!1", new BasicDBObject()); 实现插入单个对象,对象中含有数组 DBObject in = new BasicDBObject(); in.put("wtd", "wtdd"); List<String> lis = new ArrayList<String>(); lis.add("c++"); lis.add("java"); in.put("like", lis); col.insert(in); 遍历查看元素 DBObject a = new BasicDBObject(); a.put("_id", false); a.put("like", false); DBCursor dbs = col.find(null,a); for(DBObject obj:dbs) { System.out.println(obj); } 查找单个数据 DBObject aa = new BasicDBObject("name","jim"); DBCursor dbs = col.find(aa); for(DBObject obj:dbs) { System.out.println(obj); } 批量加入数据 DBObject a = new BasicDBObject(); DBObject b = new BasicDBObject(); a.put("name",111); b.put("name",222); List<DBObject> lis = new ArrayList<DBObject>(); lis.add(a); lis.add(b); col.insert(lis); 按照id删除,注意id类型 col.remove(new BasicDBObject("_id",new ObjectId("5cb586965f37024dd0baf262")));// ID是ObjectID类型 按照name删除数据 DBObject a = new BasicDBObject("name",111); col.remove(a).getN(); update增加列属性 DBObject a = new BasicDBObject(); a.put("$set", new BasicDBObject("age",25)); col.update(new BasicDBObject("name",222), a,false,false); 查找e大于80,c小于95 的数据 DBObject a = new BasicDBObject(); a.put("e", new BasicDBObject("$gt",80)); a.put("c", new BasicDBObject("$lt",95)); DBObject b = new BasicDBObject(); b.put("e", true); b.put("c", true); DBCursor dbs = col.find(a,b); for(DBObject obj:dbs) { System.out.println(obj); } 实现分页跳转 DBObject a = new BasicDBObject(); a.put("name", true); a.put("_id", 0); DBCursor dbs = col.find(null,a).limit(3).skip(3); for(DBObject obj:dbs) { System.out.println(obj); } */ } }