上一章对MongoDB做了简单的介绍,下面就让我们用java代码来操作吧
1.导入jar包
mongodb-driver是mongo官方推出的java连接mongoDB的驱动包,相当于JDBC驱动。
使用maven 引入依赖
<dependencies>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb‐driver</artifactId>
<version>3.6.3</version>
</dependency>
</dependencies>
1.一个小demo
public class MongoDemo {
public static void main(String[] args) {
MongoClient client=new MongoClient("192.168.184.134");//创建连接
MongoDatabase spitdb = client.getDatabase("spitdb");//打开数据库
MongoCollection<Document> spit = spitdb.getCollection("spit");// 获取集合
FindIterable<Document> documents = spit.find();//查询记录获取文档集 合
for(Document document:documents){ //
System.out.println("内容:"+ document.getString("content"));
System.out.println("用户ID:"+document.getString("userid"));
System.out.println("浏览量:"+document.getInteger("visits"));
}
client.close();//关闭连接
}
}
1.条件查询
查询userid为1013的记录
public class MongoDemo1 {
public static void main(String[] args) {
MongoClient client=new MongoClient("192.168.184.134");//创建连接
MongoDatabase spitdb = client.getDatabase("spitdb");//打开数据库
MongoCollection<Document> spit = spitdb.getCollection("spit");// 获取集合
BasicDBObject bson=new BasicDBObject("userid","1013");// 构建查询 条件
FindIterable<Document> documents = spit.find(bson);//查询记录获取结 果集合
for(Document document:documents){ //
System.out.println("内容:"+ document.getString("content"));
System.out.println("用户ID:"+document.getString("userid"));
System.out.println("浏览量:"+document.getInteger("visits"));
}
client.close();//关闭连接
}
}
插入数据
public class MongoDemo3 {
public static void main(String[] args) {
MongoClient client=new MongoClient("192.168.184.134");//创建连接
MongoDatabase spitdb = client.getDatabase("spitdb");//打开数据库
MongoCollection<Document> spit = spitdb.getCollection("spit");// 获取集合
Map<String,Object> map=new HashMap();
map.put("content","我要吐槽");
map.put("userid","9999");
map.put("visits",123);
map.put("publishtime",new Date());
Document document=new Document(map);
spit.insertOne(document);//插入数据
client.close();
}
}
当然,我们在实际的使用中不会这样,我在项目中是通过springDataMongoDB进行操作的
@Autowired
private MongoTemplate mongoTemplate; //mango 模板
public void thumbup(String spitId) {
/* //效率特别差 ,采用原生的
Spit spit = spitDao.findById(spitId).get();
spit.setThumbup((spit.getThumbup()==null ? 0 : spit.getThumbup())+1);
spitDao.save(spit);*/
//方式二 用mango命令
// 需要加入mango的模板
//原生的命令 db.spit.update({"_id":"1"},{$inc:{thumbup:NumberInt(1)}})
Query query = new Query();
query.addCriteria(Criteria.where("_id").is(spitId)); //{"_id":"1"}
Update update = new Update();
update.inc("thumbup",1); //{thumbup:NumberInt(1)}
mongoTemplate.updateFirst(query,update,"spit");
}