package mongodbwork; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.bson.Document; import org.bson.conversions.Bson; import com.mongodb.BasicDBObject; import com.mongodb.MongoClient; import com.mongodb.client.AggregateIterable; import com.mongodb.client.FindIterable; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoCursor; import com.mongodb.client.MongoDatabase; import com.mongodb.client.model.Accumulators; import com.mongodb.client.model.Aggregates; import com.mongodb.client.model.Filters; import com.mongodb.client.model.UpdateOptions; import com.mongodb.client.result.DeleteResult; import com.mongodb.client.result.UpdateResult; public class MongoUtil { MongoCollection<Document> collection; public MongoUtil(String db,String collectionName) { //连接到mongodb服务器 MongoClient mongoclient = new MongoClient("localhost",27017); //连接到数据库 MongoDatabase mongodatabase = mongoclient.getDatabase(db); collection = mongodatabase.getCollection(collectionName); System.out.println(collection); } public void insert(List list) { //清空集合后插入文档 collection.drop(); collection.insertMany(list); findAll(); } public void updateOne(Bson filter,Document doc,Boolean upsert) { //筛选条件,更新文档,设置选项 UpdateResult re=collection.updateOne(filter, doc,new UpdateOptions().upsert(upsert)); System.out.println(re.toString()); findFilter(filter); } public void updateMany(Bson filter,Document doc,Boolean upsert) { UpdateResult re=collection.updateMany(filter, doc,new UpdateOptions().upsert(upsert)); System.out.println(re.toString()); findFilter(filter); } public void deleteOne(Bson filter) { //删除一条符合条件文档 DeleteResult re = collection.deleteOne(filter); System.out.println(re.toString()); findAll(); } public void deleteMany(Bson filter) { //删除符合条件的所有文档 DeleteResult re = collection.deleteMany(filter); System.out.println(re.toString()); // findFilter(filter); findAll(); } public void findAll() { FindIterable<Document> find = collection.find(); MongoCursor<Document> cursor = find.iterator(); while(cursor.hasNext()) { System.out.println(cursor.next()); } } public void findSortAll(Document doc) { FindIterable<Document> find = collection.find().sort(doc); MongoCursor<Document> cursor = find.iterator(); while(cursor.hasNext()) { System.out.println(cursor.next()); } } public void findFilter(Document doc) { FindIterable<Document> find = collection.find(doc); MongoCursor<Document> cursor = find.iterator(); while(cursor.hasNext()) { System.out.println(cursor.next()); } } public void findFilter(Bson filter) { FindIterable<Document> find = collection.find(filter); MongoCursor<Document> cursor = find.iterator(); while(cursor.hasNext()) { System.out.println(cursor.next()); } } }
任务三:MangoDB java应用
15
分
任务尚未发布或者你没有权限查看任务内容。
任务讨论