mongo入门--java对mongo数据库的增删改查

// 建立一个Mongo的数据库连接对象
Mongo mongo = new Mongo("127.0.0.1:27017");

//创建相关数据库的连接

DB db = mongo.getDB("foobar");

//得到集合

DBCollection users = db.getCollection("集合名");


//1.创建一个数据库集合

DBObject dbs = new BasicDBObject();

db.createCollection("集合名称", dbs);


//2.为相应的集合添加文档

DBObject dbs = new BasicDBObject();
dbs.put("name", "uspcat.com");
dbs.put("age", 2);
List<String>  books = new ArrayList<String>();
books.add("EXTJS");
books.add("MONGODB");
dbs.put("books", books);

DBCollection coll = db.getCollection("集合名");

coll.insert(dbs);


//3.批量插入数据

List<DBObject> dbObjects = new ArrayList<DBObject>();
DBObject jim = new BasicDBObject("name","jim");
DBObject lisi = new BasicDBObject("name","lisi");
dbObjects.add(jim);
dbObjects.add(lisi);
DBCollection coll = db.getCollection("集合名");
coll.insert(dbObjects);


//4.根据ID删除数据

DBCollection coll = db.getCollection("集合名");
DBObject dbs = new BasicDBObject("_id", new ObjectId(id));
int count = coll.remove(dbs).getN();


//5.根据条件删除数据

DBObject dbs= new BasicDBObject();
dbs.put("name", "lisi");
DBCollection coll = db.getCollection("集合名");
int count = coll.remove(dbs).getN();


6.更新操作,为集合增加email属性

DBObject update = new BasicDBObject();
update.put("$set", new BasicDBObject("eamil","uspcat@126.com"));
DBCollection coll = db.getCollection("集合名");
int count = coll.update(new BasicDBObject(), update, false, true).getN();


 7.查询出persons集合中的name和age

DBObject keys = new BasicDBObject();
keys.put("_id", false);
keys.put("name", true);
keys.put("age", true);

keys.put("e", true);


DBObject ref = new BasicDBObject();
ref.put("age", new BasicDBObject("$gte",26));
ref.put("e", new BasicDBObject("$lte",80));

DBCollection coll = db.getCollection("集合名");
DBCursor cur = coll.find(ref, keys);

while (cursor.hasNext()) {
      DBObject object = cursor.next();
      System.out.print(object.get("name")+"-->");
      System.out.print(object.get("age")+"-->");
      System.out.println(object.get("e"));
}


8.分页例子

DBCollection coll = db.getCollection("集合名");
DBCursor cur = coll.find("查询条件", "查询的键");

DBCursor cursor = cur.limit("每页记录数").skip("开始位置");
while (cursor.hasNext()) {
            DBObject object = cursor.next();
            System.out.print(object.get("name")+"-->");
            System.out.print(object.get("age")+"-->");
            System.out.println(object.get("e"));
  }        
       

//关闭连接对象
mongo.close();


发布了6 篇原创文章 · 获赞 0 · 访问量 4378
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览