mongodb java操作

今天开始看mongodb的一些基础知识,首先到了官网逛逛,发现这个页面挺有用的,http://docs.mongodb.org/manual/reference/database-references/,介绍了mongodb的数据结构等各种基本知识,后来发现博客园有篇文章不错,http://www.cnblogs.com/huangxincheng/archive/2012/02/19/2357846.html,名字是8天学通mongodb,学通大概有些夸张,不过基本能够上手了,另外发现博主对于mongodb的批量插入一带而过,自己又去度娘搜了一下,发现一段不错的java代码,其实就是连接到了db之后再用简单的for循环添加,不过对于初学者要搞通api'接口比较麻烦,所以直接看代码吧,看看大神怎么写的。出于对原作者的尊重,这里是地址,http://www.tuicool.com/articles/UJRVNf,以及一份单独写批量插入的代码,需要结合前面的代码才能看懂,http://blog.csdn.net/wwwyuanliang10000/article/details/38730429。嗯,紧跟大神脚步,每天进步一点点。


MongoDB提供了Java驱动程序,以便使用Java语言访问数据库。以下是MongoDB Java操作API的一些示例代码: 1. 连接到数据库: ``` MongoClient mongoClient = new MongoClient("localhost", 27017); MongoDatabase database = mongoClient.getDatabase("mydatabase"); ``` 2. 插入数据: ``` MongoCollection<Document> collection = database.getCollection("mycollection"); Document document = new Document("name", "John Doe") .append("age", 30) .append("address", new Document("street", "123 Main St") .append("city", "Anytown") .append("state", "CA") .append("zip", 12345)); collection.insertOne(document); ``` 3. 查询数据: ``` MongoCollection<Document> collection = database.getCollection("mycollection"); Document query = new Document("name", "John Doe"); FindIterable<Document> results = collection.find(query); for (Document result : results) { System.out.println(result.toJson()); } ``` 4. 更新数据: ``` MongoCollection<Document> collection = database.getCollection("mycollection"); Document query = new Document("name", "John Doe"); Document update = new Document("$set", new Document("age", 31)); UpdateResult result = collection.updateOne(query, update); System.out.println("Modified count: " + result.getModifiedCount()); ``` 5. 删除数据: ``` MongoCollection<Document> collection = database.getCollection("mycollection"); Document query = new Document("name", "John Doe"); DeleteResult result = collection.deleteOne(query); System.out.println("Deleted count: " + result.getDeletedCount()); ``` 这些示例代码可以帮助你开始使用MongoDB Java操作API。但是,还有很多其他功能可以探索,具体取决于你的需求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值