《mongodb 小操作》要点:
本文介绍了mongodb 小操作,希望对您有用。如果有疑问,可以联系我们。
相关主题:非关系型数据库
mongodb-driver.jar操作数据库
collection是DBCollection对象
添加数据
collection.save(new BasicDBObject("author", "yinjihuan").append("title", "mongodb"));
编辑数据
collection.update(new BasicDBObject("author", "yinjihuan"),
new BasicDBObject("$set", new BasicDBObject("title", "mongodb3.0")));
删除数据
collection.remove(new BasicDBObject("author", "yinjihuan"));
查询所有数量
long count = collection.count();
查询所有数据
DBCursor cursor = collection.find();
while (cursor.hasNext()) {
DBObject data = cursor.next();
System.out.println(data.toString());
}
查询第一条数据
DBObject data = collection.findOne();
带条件查询
DBObject query = new BasicDBObject("author", "yinjihuan");
cursor = collection.find(query);
大于(gt)查询
query = new BasicDBObject("visit_count", new BasicDBObject("$gt", 10));
cursor = collection.find(query);
小于(lt)查询
query = new BasicDBObject("visit_count", new BasicDBObject("$lt", 10));
cursor = collection.find(query);
查询固定的列
query = new BasicDBObject("author", "yinjihuan");
DBObject fields = new BasicDBObject("author", 1);
cursor = collection.find(query, fields);
分页查询,当数据量较大的时候不建议使用skip,会很慢的
建议按id排序,每查询一页记住最后一条id,然后大于id在limit
query = new BasicDBObject("author", "yinjihuan");
cursor = collection.find(query, fields).skip(0).limit(10);
创建索引
collection.createIndex(new BasicDBObject("author_idx", 1));
维易PHP培训学院每天发布《mongodb 小操作》等实战技能,PHP、MYSQL、LINUX、APP、JS,CSS全面培养人才。