Java中使用MongoDB进行增删改查

本文介绍了如何在Java中使用MongoDB进行数据操作,包括使用find()进行条件查找,内嵌文档与数组查询,以及lt、gt等属性比较。还详细讲解了updateOne()、updateMany()、replaceOne()、deleteMany()、deleteOne()和drop()等方法,涵盖了增、删、改、查的各种场景。
摘要由CSDN通过智能技术生成
参考官网:  https://docs.mongodb.org/getting-started/java
初次使用MongoDB,大概的写一下如何在Java中应用MongoDB进行数据的增删改查。
关于MongoDB的介绍就不细说了,各位可以自行在官网查看或者百度搜索。

1.连接MongoDB数据库
    MongoClient mongoClient = new MongoClient( "127.0.0.1" , 27017 );
        MongoDatabase db = mongoClient. getDatabase( "Rests" );
        MongoCollection <Document > mongoCollection = db .getCollection ("restaurants" );

数据document模板
{
  "address": {
     "building": "1007",
     "coord": [ -73.856077, 40.848447 ],
     "street": "Morris Park Ave",
     "zipcode": "10462"
  },
  "borough": "Bronx",
  "cuisine": "Bakery",
  "grades": [
     { "date": { "$date": 1393804800000 }, "grade": "A", "score": 2 },
     { "date": { "$date": 1378857600000 }, "grade": "A", "score": 6 },
     { "date": { "$date": 1358985600000 }, "grade": "A", "score": 10 },
     { "date": { "$date": 1322006400000 }, "grade": "A", "score": 9 },
     { "date": { "$date": 1299715200000 }, "grade": "B", "score": 14 }
  ],
  "name": "Morris Park Bake Shop",
  "restaurant_id": "30075445"
}


2.Insert Data--增加数据
    import org.bson.Document;
    import java.text.DateFormat;
    import java.text.ParseException;    
    import java.text.SimpleDateFormat;
    import java.util.Locale;
    import static java.util.Arrays.asList;

DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ENGLISH);
db.getCollection("restaurants").insertOne(
        new Document("address",
                new Document()
                        .append("street", "2 Avenue")
                        .append("zipcode", "10075")
                        .append("building", "1480")
                        .append("coord", asList(-73.9557413, 40.7720266)))
                .append("borough", "Manhattan")
                .append("cuisine", "Italian")
                .append("grades", asList(
                        new Document()
                                .append("date", format.parse("2014-10-01T00:00:00Z"))
                                .append("grade", "A")
                                .append("score", 11),
                        new Document()
                                .append("date", format.parse("2014-01-16T00:00:00Z"))
                                .append("grade", "B")
                                .append("score", 17)))
                .append("name", "Vella")
                .append("restaurant_id", "41704620"));


3.Find or Query DAta --- 查找数据

import org.bson.Document;
import com.mongodb.Block;
import com.mongodb.client.FindIterable;
import static com.mongodb.client.model.Filters.*;
import static com.mongodb.client.model.Sorts.ascending;
import static java.util.Arrays.asList;
  • find() -- 查找collection所有数据
FindIterable<Document> iterable = db.getCollection("restaurants").find();
//---遍历---
iterable.forEach(new Block<Document>() {
    @Override
    public void apply(final Document document) {
        System.out.println(document);
    }
});

  • find(new Document( <field>, <value> )) 或者find(eq( <field>, <value> )) ---  条件查找
FindIterable<Document> iterable = db.getCollection("restaurants").find(
        new Document("borough", "Manhattan"));
或者
db.getCollection("restaurants").find(eq("borough", "Manhattan"));
遍历与以上相同

  • 查找内嵌document  方法  address.zipcode
FindIterable<Document> iterable = db.getCollection("restaurants").find(
        new Document("address.zipcode", "10075"));
或者
db.getCollection("restaurants").find(eq("address.zipcode", "10075"));
遍历与以上类似

  • 内嵌数组查询
FindIterable<Document> iterable = db.getCollection("restaurants").find(
        new Document("grades.grade", "B"));
或者
db.getCollection("restaurants").find(eq("grades.grade", "B"));

  • 属性比较 lt  gt
lt(<field>, <value>)
gt(<field>, <value>)

使用
FindIterable<Document> iterable = db.getCollection("restaurants").find(
        new Document("grades.score", new Document("$gt", 30)));
或者
db.getCollection("restaurants").find(gt("grades.score", 30));

FindIterable<Document> iterable = db.getCollection("restaurants").find(
        new Document("grades.score", new Document("$lt", 10)));
或者
db.getCollection("restaurants").find(lt("grades.score", 10));


  • 混合条件查询 and  or
and 查询
FindIterable<Document> iterable = db.getCollection("restaurants").find(
        new Document("cuisine", "Italian").append("address.zipcode", "10075"));
或者
db.getCollection("restaurants").find(and(eq("cuisine", "Italian"), eq("address.zipcode", "10075")));

or查询
FindIterable<Document> iterable = db.getCollection("restaurants").find(
        new Document("$or", asList(new Document("cuisine", "Italian"),
                new Document("address.zipcode", "10075"))));
或者
db.getCollection("restaurants").find(or(eq("cuisine", "Italian"), eq("address.zipcode", "10075")));

  • sort排序  1--升序  -1--降序
FindIterable<Document> iterable = db.getCollection("restaurants").find()
        .sort(new Document("borough", 1).append("address.zipcode", 1));
或者
db.getCollection("restaurants").find().sort(ascending("borough", "address.zipcode"));


4.更新数据 update
更新有是三种方法  updateOne()   updateMany()  replaceOne()

import org.bson.Document;

import static java.util.Arrays.asList;

  • updateOne()使用
    • 如果查出的是列表,则默认更新的是第一个document
db.getCollection("restaurants").updateOne(new Document("name", "Juni"),
        new Document("$set", new Document("cuisine", "American (New)"))
            .append("$currentDate", new Document("lastModified", true)));
    • 根据条件详细查找单个对象更新内容
db.getCollection("restaurants").updateOne(new Document("restaurant_id", "41156888"),
        new Document("$set", new Document("address.street", "East 31st Street")));

  • updateMany()使用
db.getCollection("restaurants").updateMany(new Document("address.zipcode", "10016").append("cuisine", "Other"),
        new Document("$set", new Document("cuisine", "Category To Be Determined"))
                .append("$currentDate", new Document("lastModified", true)));
  • replaceOne()使用
db.getCollection("restaurants").replaceOne(new Document("restaurant_id", "41704620"),
        new Document("address",
                new Document()
                        .append("street", "2 Avenue")
                        .append("zipcode", "10075")
                        .append("building", "1480")
                        .append("coord", asList(-73.9557413, 40.7720266)))
                .append("name", "Vella 2"));


5.Remove Data--删除数据     
主要用deleteOne()和deletemany()两个方法删除数据
  • deleteMany()--删除符合条件的数据
db.getCollection("restaurants").deleteMany(new Document("borough", "Manhattan"));     
删除所有数据 :
db.getCollection("restaurants").deleteMany(new Document());
  • deleteOne()--根据特定条件查找出单个数据删除
db.getCollection("restaurants").deleteMany(new Document("restaurant_id", "41156888"));     

  • drop() -- 删除collection
db.getCollection("restaurants").drop();


这里只是初级应用,复杂一点的后续了解再记录。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值