SpringDataMongoDB basic instance code
1. Download the example from the official website below, and the download address is as follows: http://www.springsource.org/samples 2. Troubleshooting, the The SpringExample just downloaded has an error. First of all, it is not a maven project. Right-click to convert it into a maven project, and add some dependencies, such as spring-aop, spring-context, spring-core, log4j and other dependencies. At the same time, update your dependent packages and configurations. After the final operation is successful, run the next step. 3. Code explanation. 3.1 Method 1 (open mongo.exe in annotation mode, and create database yourdb and document yourCollection at the same time), the code is as follows: package com.mkyong.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.document.mongodb.MongoTemplate; import org.springframework.data.document.mongodb.config.AbstractMongoConfiguration; import com.mongodb.Mongo; /** * Spring MongoDB configuration file * */ @Configuration public class SpringMongoConfig extends AbstractMongoConfiguration { @Override public @Bean Mongo mongo() throws Exception { Return new Mongo(“localhost”); } @Override public @Bean MongoTemplate mongoTemplate() throws Exception { Return new MongoTemplate(mongo(),”yourdb”,”yourCollection”); } } 3.2 Method 2 (configuration file method), the code is as follows: <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xmlns:cOntext=”http://www.springframework.org/schema/context” xmlns:mOngo=”http://www.springframework.org/schema/data/mongo” xsi:schemaLocation=”http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd”> 3.3 Writing entity classes package com.mkyong.user; public class User { private String id; private String firstname; private String lastname; private int…
MongoDB Advanced Aggregate Query Usage Guide
MongoDB version is: 2.0.8 The system is: 64-bit Ubuntu 12.04 First show him my table structure [Oh sorry, Mongo is called a collection] As you can see, I try to simulate real life scenarios as much as possible. This is a Person entity, he has basic manId, manName, There are friends [myFriends], there are favorite fruits [fruits], and each fruit has a favorite weight. Unfortunately, you also saw a “_class” field? Because I am a Java developer, I also like to use Spring, so I chose Spring Data Mongo’s class library [it can be regarded as a framework, but I don’t think so]. Now many people are tired of seeing Spring and are starting to get bored. Yes, Spring has great ambitions, and he almost wants to monopolize everything in Java. There is no way I can’t do without him since I used Spring, so that I basically don’t need to learn other frameworks. I have learned a lot about Spring, such as: Spring Security/Spring Integration/Spring Batch and so on. . . He who didn’t invent the wheel has already provided many scenarios in programming. I used those scenarios to solve many problems in my work and made my work…
Research on MongoDB query performance
Previous: Mongodb VS Mysql query performance, tested the query performance of mongodb and mysql. Result Description mongodb The performance is OK, and it can be used instead of mysql. But this test is at the million level, and my scene is at the KW level. So it is necessary to test the effect of mongodb at the kw level. My test environment is 4G memory (a lot of memory is occupied by other programs), 2kw data, and the query randomly generates ids (query 20 ids at a time). The test in such an environment is not ideal, and it is disappointing. The average query time is 500ms (compared to mysql Not bad, especially under concurrent queries, the performance is poor. very low throughput). View its index size (query with db.mycoll.stats()): 2kw There are about 1.1G indexes in the data, and the stored data is about 11G. During the test, it was found that iowait accounts for about 50%, which seems to be the bottleneck of io. Also see mongodb Not much memory used (less than the size of the index, it seems the machine is not big enough to test). Change to a machine with available 6G memory. Under 50…
Spring and MongoDB implement aggregation query
Integrate MongoDB and Spring, find the corresponding version according to the development document. According to official documents, we know that Spring must be version 3.0.x or above, and MongoDB must be version 1.6.5 or above. If you want to integrate Spring and Mongodb, you must download the corresponding jar. There are mainly two jars used here, one is spring-data-document and spring- There are two types of jars in data-commons, but the versions of the two types of jars must match to avoid jar conflicts, because the jar directory of the version behind commons has changed for all versions This must be corresponding to the following is the jar download address http://www.springsource.org/spring-data/mongodb http://www.springsource.org/spring-data/commons The following is the jar I downloaded and add the mongodb java driver package, spring I won’t say more about jar addition The Spring configuration file is as follows: 1. 2. <beans xmlns="http://www.springframework.org/schema/beans" 3. xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” 4. xmlns:cOntext=”http://www.springframework.org/schema/context” 5. xmlns:mOngo=”http://www.springframework.org/schema/data/mongo” 6. xsi:schemaLocation= 7. “http://www.springframework.org/schema/context 8. http://www.springframework.org/schema/context/spring-context-3.0.xsd 9. http://www.springframework.org/schema/data/mongo 10. http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd 11. http://www.springframework.org/schema/beans 12. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd”> 13. 14. 15. 16. 17. <bean id="mongoTemplate" class=”org.springframework.data.document.mongodb.MongoTemplate”> 18. 19. 20. 21. 22. <bean id="personRepository" class=”com.mongo.repository.PersonRepository”> 23. 24. 26. 27. the 28. 29. the 30. 31. 32. 33. 34. 35. the Define the interface…
MongoDB uses Update to update records
Same as above, then learn MongoDB’s data update syntax. 1. Update a record –1.1 Query documents with id=1 > db.test_2.find({id:1}); { “_id” : ObjectId(“50a0d46ceb825d827b0c3f9b”), “id” : 1, “name” : “francs” } { “_id” : ObjectId(“50a12e34f73f2e4aa1ff71bc”), “id” : 1, “name” : “francs” } –1.2 Update the name field of documents with id=1 as ‘name_2’ > db.test_2.update({id:1},{$set:{name:’name_2′}}); –1.3 Query documents with id=1 again > db.test_2.find({id:1}); { “_id” : ObjectId(“50a0d46ceb825d827b0c3f9b”), “id” : 1, “name” : “name_2” } { “_id” : ObjectId(“50a12e34f73f2e4aa1ff71bc”), “id” : 1, “name” : “francs” } Remarks: Only one matching record was found to be updated. 2. Update multiple records –2.1 Query documents with id=2 > db.test_2.find({id:2}); { “_id” : ObjectId(“50a0d46ceb825d827b0c3f9c”), “id” : 2, “name” : “fpZhou” } { “_id” : ObjectId(“50a12e7cf73f2e4aa1ff71bd”), “id” : 2, “name” : “fpZhou” } { “_id” : ObjectId(“50a12f47f73f2e4aa1ff71be”), “id” : 2, “name” : “fpZhou” } –2.2 Update the name field of documents with id=2 to ‘name_3’ > db.test_2.update({id:2},{$set:{name:’name_3′}},{multi:true}); –2.3 Query documents with id=2 again > ;db.test_2.find({id:2}); { “_id” : ObjectId(“50a0d46ceb825d827b0c3f9c”), “id” : 2, “name” : “name_3” } { “_id” : ObjectId(“50a12e7cf73f2e4aa1ff71bd”), “id” : 2, “name” : “name_3” } { “_id” : ObjectId(“50a12f47f73f2e4aa1ff71be”), “id” : 2, “name” : “name_3”} Note: By default, update() only updates the first…
Detailed explanation of the update method of MongoDB database
In the previous article “mongodb In “Query Syntax”, I introduced the common query syntax of Mongodb. The update operation of Mongodb is also a bit complicated. I will introduce it here based on my own experience and show it to friends who use mongodb. It is also convenient to refer to when you use it later: Note: The grammar introduction in this article and the previous article are all in mongodb In the shell environment, there are some differences in usage methods when using real language programming (such as java, php, etc.), but the syntax (such as query conditions, $in, $inc, etc.) is the same. This article is introduced with reference to the official documents. The reason why there are official documents is introduced here. On the one hand, it is used as a translation. It’s hard to understand from the official documentation, I can make some supplements in actual operation. Well, without further ado, let’s start: There are two commands for mongodb update: 1).update() command db.collection.update( criteria, objNew, upsert, multi ) criteria : query criteria for update, similar to the behind where in the sql update query objNew : update object and some update operators (such as $, $inc…),…
Spring support for MongoDB
Spring’s support for mongoDB includes the following features: The configuration of mongodb in spring supports the way of annotation @Configuration and xml MongoTemplate helper class extends Mongo The production efficiency of operations provides conversion between document and pojo types Add dependencies to pom.xml the the org.springframework.data the spring-data-mongodb 1.1.0.RELEASE You can set the log level to debug to view more log information log4j.category.org.springframework.data.document.mOngodb=DEBUG log4j.appender.stdout.layout.COnversionPattern=%d{ABSOLUTE} %5p %40.40c:%4L – %m%n app-mongodb.xml <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" the xmlns:cOntext=”http://www.springframework.org/schema/context” xmlns:mOngo=”http://www.springframework.org/schema/data/mongo” the xsi:schemaLocation=”http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd”> the <mongo:options connections-per-host="${mongo. connectionsPerHost}" threads-allowed-to-block-for-connection-multiplier=”${mongo.threadsAllowedToBlockForConnectionMultiplier}” connect-timeout=”${mongo.connectTimeout}” max-wait-time=”${mongo.maxWaitTime}” auto-connect-retry=”${mongo.autoConnectRetry}” socket-keep-alive=”${mongo.socketKeepAlive}” socket-timeout=”${mongo.socketTimeout}” slave-ok=”${mongo. slaveOk}” write-number=”1″ write-timeout=”0″ write-fsync=”true” /> the the Person.java package com.dempe.summer.person.model; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; /** * @author: Zheng Dongping * @version 1.0 date: 2013-12-20 */ @Document(collection = “person”) public class Person { @Id private String id; private String name; private Integer age; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return…
How to use MongoDBUpdate
I recently started reading some articles about MongoDB, and I feel more and more that it is what I need. However, I don’t know much about it first, and what I see are superficial phenomena, let’s get to know it slowly. I started reading the introduction to MongoDB written by Carl yesterday. It has 33 pages in total. I feel that the article is not very clear, and I need to try and experience it myself. For traditional databases, CRUD (=Create+Read+Update+Delete) is the core, and U is the most worthy of attention! Today, I read the introduction of the Update part and practiced it. Update has 4 parameters: the first, selector, the second, newValue, the third, upserts, the fourth, multipleUpdate The selector is the same as the CRD, it is a search selector that specifies the query conditions; newValue is the content to be updated, including two basic situations, that is, whether there are parameters such as $set, $inc, and $push: Case 1, if there is no parameter, then newValue replaces the content of the original selector; Case 2, if there are parameters, then $set is to update newValue for the specified field; $inc requires the specified field to be…
Explanation of update operation of MongoDB database
I didn’t record the update operation before, so I have time to record the use of mongodb update today Look at the syntax first: db.collection.update( , , ) The syntax is very simple, but it will be more complicated to use with some functions. Let me explain. query: conditional limitation, that is, the condition that the row needs to be updated, which is equivalent to the conditional judgment after where in SQL update: equivalent to the set statement in the SQL table options: What needs to be noted here is the update operation of mongodb. By default, only the first row that meets the conditions is updated. If you want to update all the rows that meet the conditions, you need to specify multi to be true, and one parameter is upsert, which means if it does not exist The records that match the query are inserted into the updated data. The default is false and not inserted. You can specify true The simplest example, let’s take a look: PRIMARY> db.test.save({id:1,”name”:”hank”}) PRIMARY> db.test.find() { “_id” : ObjectId(“50c055656b41f59a0235881b”), “id” : 1, “name” : “hank” } PRIMARY> db.test.update({id:1},{“name”:”dazuiba”}) PRIMARY> db.test.find() { “_id” : ObjectId(“50c055656b41f59a0235881b”), “name” : “dazuiba” } An example of updating…
Use of MongoDB database fragmentation and clustering
Sharded Cluster Data fragmentation in Mongodb is called chunk, which is a continuous data record in a Collection, but it has a size limit that cannot exceed 200M. If it exceeds, a new fragment will be generated. The following is a simple shard cluster example The composition of the shard cluster: Shard server: mongod instance, used to store actual data blocks Config server: mongod instance, used to store the entire Cluster Metadata, including chunk information. route server: mongos instance, as the front-end route of the entire cluster, from which the entire cluster is connected. This makes the entire cluster look like a single-process database. Remarks: route as a route will forward the request to the actual target service process, combine multiple results and send them back to the client. The route does not store any data and status, all information is from Config when starting server, when there is information update on the Config server, it will also be synchronized to the route server. the Build a simple cluster Cluster directory: There are four mongodb in total, the directories are /home/scotte.ye/mongo1, mongo2, mongo3, mongo4 Among them, mongo1 and mongo2 are used as shard servers mongo3 as config server mongo4 as…