Java操作mongodb增删改查的操作

MongoDB:

1.MongoDB的提供了一个面向文档存储,操作起来比较简单和容易。

2.如果负载的增加,它可以分布在计算机网络中的其他节点上这就是所 谓的分片。

3. MongoDB支持各种编程语言:RUBY,PYTHON,JAVA,C++, PHP,C#等多种语言。

4.你可以通过本地或者网络创建数据镜像,这使得MongoDB有更强的 扩展性。

Java操作MongoDB

// 连接对象

MongoClient mc = new MongoClient("localhost", 27017);

//查看所有库

MongoIterable<String> listDatabaseNames = mc.listDatabaseNames();

MongoCursor<String> iterator = listDatabaseNames.iterator();

while(iterator.hasNext()) {

System.out.println(iterator.next());

                }

// 库对象

MongoDatabase db = mc.getDatabase("库名");

//查看所有集合

MongoIterable<String> listCollectionNames = db.listCollectionNames();

for(String s : listCollectionNames) {

System.out.println(s);

}

// 集合对象

MongoCollection<Document> collection = db.getCollection("集合名");

// 添加一条数据

collection.insertOne(document对象);

// 一次添加多条数据

collection.insertMany(listdoc<document>集合);

//删除数据

DeleteResult deleteOne = collection.deleteOne(new Document("name","张三"));

//删除多条数据

DeleteResult deleteMany = collection.deleteMany(new Document("name","张三"));

Filters

该过滤器类为所有的MongoDB的查询操作静态工厂方法。每个方法返回BSON类型,又可以传递给期 望一个查询过滤器的任何方法的一个实例。

 eq:匹配等于指定值的值。

 gt:匹配大于指定值的值。

 gte:匹配大于或等于指定值的值。

 lt:匹配小于规定值的值。

 lte:匹配是小于或等于规定值的值。

 ne:匹配不等于指定值的所有值。

 in:匹配任何在数组中指定的值。

 nin:没有匹配数组中的规定值

//删除

Bson eq = Filters.eq("name", "哈哈哈");

// 多条件修改

Bson and = Filters.and(Filters.gte("age", 20),Filters.lte("age", 30));

UpdateResult updateOne = collection.updateOne(

and, new Document("$set",new Document("age", 20)),

new UpdateOptions().upsert(true));

new UpdateOptions().upsert(true)查不到数据新增

//修改数据

UpdateResult updateOne = collection.updateOne(

eq, new Document("$set",new Document("age", 20)));

//修改多条数据

UpdateResult updateMany = collection.updateMany(

and, new Document("$inc",new Document("age",100)));

//全查

MongoCollection<Document>  = Db.getCollection("comment");

//多条件查询

Bson and = Filters.and(Filters.gte("age", 20),Filters.lte("age", 30));

FindIterable<Document> find = collection.find(and)

//模糊查询

Bson eq = Filters.regex("name", "张");

FindIterable<Document> find = collection.find(eq)

//排序查询

Document document = new Document("birthday",-1);

FindIterable<Document> find = collection.find(eq).sort(document);

//分页查询 .limit(2).skip(2)

FindIterable<Document> find = collection.find(eq).limit(2).skip(2);

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值