前言参考Java对mongoDB增删改查操作,这里说明一下$set,$inc,$unset,$push,$pop,$pull,$pullAll,$rename的使用示例。
MongoDB 是一个基于分布式文件存储的数据库。由 C++ 语言编写。旨在为 WEB 应用提供可扩展的高性能数据存储解决方案。
MongoDB 是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当中功能最丰富,最像关系数据库的。
本文介绍了Java操作MongoDB数据库的使用。
首先我们已经初始化好了数据,如图
这次在源代码的testUpdate方法中进行测试
public static void testUpdate() {
MongoDatabase mongoDatabase = getDB();
// 这里的 "user" 表示集合的名字,如果指定的集合不存在,mongoDB将会在你第一次插入文档时创建集合。
MongoCollection<Document> collection = mongoDatabase.getCollection("user");
// 修改过滤器
Bson filter = Filters.eq("age", 20);
// 只修改特定的Field
Document document = new Document("$set", new Document("age", 25));
// 可以对文档的某个值为数字型(只能为满足要求的数字)的键进行增减的操作。如果给定正数表示新增,如果给定负数表示减少。
Document document2 = new Document("$inc", new Document("age", -5));
// 主要是用来删除键。让键的值为空。在编写命令时$unset里field取值任意,无论给定什么值都表示删除。
Document document3 = new Document("$unset", new Document("sex", "/"));
// 向文档的某个数组类型的键添加一个数组元素,不过滤重复的数据。添加时键存在,要求键值类型必须是数组;键不存在,则创建数组类型的键。
// 这个document4执行两次Update能看到效果
Document document4_1 = new Document("$push", new Document("bodyType", "胖子1"));
Document document4_2 = new Document("$push", new Document("bodyType", "胖子2"));
// 删除数据元素。可取值只能是1或−1。1表示尾部删除,−1表示头部删除删除hobby中第一个元素。其中pop中key是要操作的数组类型属性。
Document document5 = new Document("$pop", new Document("bodyType", 1));
// 从数组中删除满足条件的元素,只要满足条件都删除。
Document document6 = new Document("$pull", new Document("bodyType", "胖子"));
// 可以设置多个条件。其中属性取值一定要是数组类型。
ArrayList<String> paraList = new ArrayList<String>();
paraList.add("胖子1");
paraList.add("胖子2");
Document document7 = new Document("$pullAll", new Document("bodyType", paraList));
// 对键进行重新命名。任何类型的键都能重命名。
Document document8 = new Document("$rename", new Document("name", "username"));
// 修改多个文档
collection.updateMany(filter, document);
closeDB();
}
注意下过滤器,就是类似SQL中的条件语句,如果更新不到数据,那应该看过滤条件对不对
Bson filter = Filters.lt("age", 100);
当执行$push时,要执行两次,这样才能看到效果,在工具上点击下面那个图标
END