(1) 创建工程 mongoDemo, 引入依赖
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver</artifactId>
<version>3.6.3</version>
</dependency>
(2) 创建测试类
public class MongoDemo(){
public static void main(){
MongoClient client=new MongoClient("127.0.0.1");
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("content"));
System.out.println("浏览量:"+document.getString("content"));
}
client.close();
}
条件查询
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();
}
}
查询浏览量大于1000的记录
public class MongoDemo2 {
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("visits",new BasicDBObject("$gt",1000));
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","11");
map.put("visits","123");
map.put("publishtime",new Date());
Document document = new Document(map);
spit.insertOne(document);
client.close();
}
}