<dependencies>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.2.2</version>
</dependency>
</dependencies>
package com.hiekn;
import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import java.util.ArrayList;
import java.util.HashMap;
public class MongoTest {
public static void main(String[] args) {
MongoClient mongoClient = new MongoClient("192.168.20.70", 19130);
MongoDatabase dbTest = mongoClient.getDatabase("test");
MongoCollection<Document> collection = dbTest.getCollection("test_collection");
if(collection == null){
dbTest.createCollection("test_collection");
}
Document doc = new Document();
doc.append("Name","name1");
doc.append("Age",20);
collection.insertOne(doc);
Document doc2 = new Document();
doc2.append("Name","name2");
doc2.append("Age",30);
ArrayList dataList = new ArrayList();
dataList.add(doc);
dataList.add(doc2);
collection.insertMany(dataList);
BasicDBObject delSql = new BasicDBObject("Name", "name1");
collection.findOneAndDelete(delSql);
collection.deleteMany(delSql);
BasicDBObject updatOldSql = new BasicDBObject("Name", "name2");
BasicDBObject updateNewOneSql = new BasicDBObject("$set", new BasicDBObject("Name", "name1"));
collection.updateOne(updatOldSql,updateNewOneSql);
BasicDBObject updateNewManySql = new BasicDBObject("$set", new BasicDBObject("Name", "name1").append("Age", 66));
collection.updateMany(updatOldSql,updateNewManySql);
BasicDBObject querySql = new BasicDBObject("Name", "name1");
FindIterable<Document> queryRst = collection.find(querySql);
MongoCursor<Document> cursor = queryRst.iterator();
while (cursor.hasNext()){
System.out.println(cursor.next());
}
BasicDBObject query3 = new BasicDBObject();
query3.put("name","Tom");
HashMap<String, Object> queryMap = new HashMap<String, Object>();
queryMap.put("$gt","1496911821071");
queryMap.put("$lt","1496915447871");
query3.put("timeStamp",new BasicDBObject(queryMap));
query3.put("businessRuleName",new BasicDBObject("$regex","rule"));
FindIterable<Document> result = collection.find(query3);
}
}