MongoDB的增删改查

MongoDB操作指南
本文介绍了一个基于MongoDB API 3.2.0的Java应用程序,演示了如何连接MongoDB数据库并执行基本操作,如插入、查询、更新和删除文档。


如何安装mongodb,请参考http://blog.youkuaiyun.com/zpf336/article/details/50765789

注:此文基于mongoDb API 3.2.0进行的测试。

测试代码如下:

pom.xml文件

  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2. xsi:schemaLocation= "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  3. <modelVersion>4.0.0 </modelVersion>
  4. <groupId>mongo </groupId>
  5. <artifactId>mongodb </artifactId>
  6. <version>0.0.1-SNAPSHOT </version>
  7. <packaging>jar </packaging>
  8. <name>mongodb </name>
  9. <url>http://maven.apache.org </url>
  10. <properties>
  11. <project.build.sourceEncoding>UTF-8 </project.build.sourceEncoding>
  12. </properties>
  13. <dependencies>
  14. <dependency>
  15. <groupId>junit </groupId>
  16. <artifactId>junit </artifactId>
  17. <version>4.12 </version>
  18. <scope>test </scope>
  19. </dependency>
  20. <dependency>
  21. <groupId>org.mongodb </groupId>
  22. <artifactId>mongo-java-driver </artifactId>
  23. <version>3.2.0 </version>
  24. </dependency>
  25. </dependencies>
  26. </project>


MongoDb API 类:

  1. package mongo.mongodb;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import org.bson.Document;
  5. import org.bson.conversions.Bson;
  6. import com.mongodb.MongoClient;
  7. import com.mongodb.client.FindIterable;
  8. import com.mongodb.client.MongoCollection;
  9. import com.mongodb.client.MongoCursor;
  10. import com.mongodb.client.MongoDatabase;
  11. import com.mongodb.client.result.UpdateResult;
  12. public class MongoDb {
  13. private static MongoCollection<Document> collection;
  14. /**
  15. * 链接数据库
  16. *
  17. * @param databaseName
  18. * 数据库名称
  19. * @param collectionName
  20. * 集合名称
  21. * @param hostName
  22. * 主机名
  23. * @param port
  24. * 端口号
  25. */
  26. public static void connect(String databaseName, String collectionName,
  27. String hostName, int port) {
  28. @SuppressWarnings( "resource")
  29. MongoClient client = new MongoClient(hostName, port);
  30. MongoDatabase db = client.getDatabase(databaseName);
  31. collection = db.getCollection(collectionName);
  32. System.out.println(collection);
  33. }
  34. /**
  35. * 插入一个文档
  36. *
  37. * @param document
  38. * 文档
  39. */
  40. public static void insert(Document document) {
  41. collection.insertOne(document);
  42. }
  43. /**
  44. * 查询所有文档
  45. *
  46. * @return 所有文档集合
  47. */
  48. public static List<Document> findAll() {
  49. List<Document> results = new ArrayList<Document>();
  50. FindIterable<Document> iterables = collection.find();
  51. MongoCursor<Document> cursor = iterables.iterator();
  52. while (cursor.hasNext()) {
  53. results.add(cursor.next());
  54. }
  55. return results;
  56. }
  57. /**
  58. * 根据条件查询
  59. *
  60. * @param filter
  61. * 查询条件 //注意Bson的几个实现类,BasicDBObject, BsonDocument,
  62. * BsonDocumentWrapper, CommandResult, Document, RawBsonDocument
  63. * @return 返回集合列表
  64. */
  65. public static List<Document> findBy(Bson filter) {
  66. List<Document> results = new ArrayList<Document>();
  67. FindIterable<Document> iterables = collection.find(filter);
  68. MongoCursor<Document> cursor = iterables.iterator();
  69. while (cursor.hasNext()) {
  70. results.add(cursor.next());
  71. }
  72. return results;
  73. }
  74. /**
  75. * 更新查询到的第一个
  76. *
  77. * @param filter
  78. * 查询条件
  79. * @param update
  80. * 更新文档
  81. * @return 更新结果
  82. */
  83. public static UpdateResult updateOne(Bson filter, Bson update) {
  84. UpdateResult result = collection.updateOne(filter, update);
  85. return result;
  86. }
  87. /**
  88. * 更新查询到的所有的文档
  89. *
  90. * @param filter
  91. * 查询条件
  92. * @param update
  93. * 更新文档
  94. * @return 更新结果
  95. */
  96. public static UpdateResult updateMany(Bson filter, Bson update) {
  97. UpdateResult result = collection.updateMany(filter, update);
  98. return result;
  99. }
  100. /**
  101. * 更新一个文档, 结果是replacement是新文档,老文档完全被替换
  102. *
  103. * @param filter
  104. * 查询条件
  105. * @param replacement
  106. * 跟新文档
  107. */
  108. public static void replace(Bson filter, Document replacement) {
  109. collection.replaceOne(filter, replacement);
  110. }
  111. /**
  112. * 根据条件删除一个文档
  113. *
  114. * @param filter
  115. * 查询条件
  116. */
  117. public static void deleteOne(Bson filter) {
  118. collection.deleteOne(filter);
  119. }
  120. /**
  121. * 根据条件删除多个文档
  122. *
  123. * @param filter
  124. * 查询条件
  125. */
  126. public static void deleteMany(Bson filter) {
  127. collection.deleteMany(filter);
  128. }
  129. }

测试类:

  1. package mongo.mongodb;
  2. import java.util.List;
  3. import org.bson.Document;
  4. import org.junit.Before;
  5. import org.junit.Test;
  6. import com.mongodb.client.result.UpdateResult;
  7. public class MongoTest
  8. {
  9. @Before
  10. public void before(){
  11. MongoDb.connect( "test", "darren", "172.16.155.151", 27017);
  12. }
  13. @Test
  14. public void testInsert(){
  15. Document document = new Document();
  16. document.append( "name", "wang").append( "gender", "female");
  17. MongoDb.insert(document);
  18. }
  19. @Test
  20. public void testFindAll(){
  21. List<Document> results = MongoDb.findAll();
  22. for(Document doc : results){
  23. System.out.println(doc.toJson());
  24. }
  25. }
  26. @Test
  27. public void testFindBy(){
  28. Document filter = new Document();
  29. filter.append( "name", "li si");
  30. List<Document> results = MongoDb.findBy(filter);
  31. for(Document doc : results){
  32. System.out.println(doc.toJson());
  33. }
  34. }
  35. @Test
  36. public void testUpdateOne(){
  37. Document filter = new Document();
  38. filter.append( "gender", "male");
  39. //注意update文档里要包含"$set"字段
  40. Document update = new Document();
  41. update.append( "$set", new Document( "gender", "female"));
  42. UpdateResult result = MongoDb.updateOne(filter, update);
  43. System.out.println( "matched count = " + result.getMatchedCount());
  44. }
  45. @Test
  46. public void testUpdateMany(){
  47. Document filter = new Document();
  48. filter.append( "gender", "female");
  49. //注意update文档里要包含"$set"字段
  50. Document update = new Document();
  51. update.append( "$set", new Document( "gender", "male"));
  52. UpdateResult result = MongoDb.updateMany(filter, update);
  53. System.out.println( "matched count = " + result.getMatchedCount());
  54. }
  55. @Test
  56. public void testReplace(){
  57. Document filter = new Document();
  58. filter.append( "name", "zhang");
  59. //注意:更新文档时,不需要使用"$set"
  60. Document replacement = new Document();
  61. replacement.append( "value", 123);
  62. MongoDb.replace(filter, replacement);
  63. }
  64. @Test
  65. public void testDeleteOne(){
  66. Document filter = new Document();
  67. filter.append( "name", "li");
  68. MongoDb.deleteOne(filter);
  69. }
  70. @Test
  71. public void testDeleteMany(){
  72. Document filter = new Document();
  73. filter.append( "gender", "male");
  74. MongoDb.deleteMany(filter);
  75. }
  76. }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值