Spring-boot Configure MongoDB Connection, save, find, Count operations

Source: Internet
Author: User
Tags mongodb

In a few simple steps, you can configure your MongoDB connection and then manipulate the data using Mongotemplate:

1, the introduction of dependency:

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId> Spring-boot-starter-data-mongodb</artifactid>
		</dependency>

2. Configure connection information in APPLICATION.YML:

Spring:
  data:
    MongoDB:
      uri:mongodb://192.168.0.9:27017/test
Where: Test is the name of the DB.

3. Create an entity class:

Package com.xjj.entity;

Import java.util.Date;

public class Person {
	private int id;
	Private String firstName;
	Private String lastName;
	Private Date birthDate;
	private char sex;		' M ', ' F '
	private String Phoneno;
	
	Public String Getfirstname () {
		return firstName;
	}
	public void Setfirstname (String firstName) {
		this.firstname = firstName;
	}
	Public String Getlastname () {
		return lastName;
	}
	public void Setlastname (String lastName) {
		this.lastname = lastName;
	}
	Public Date getbirthdate () {
		return birthDate;
	}
	public void Setbirthdate (Date birthDate) {
		this.birthdate = birthDate;
	}
	Public Char Getsex () {
		return sex;
	}
	public void Setsex (char sex) {
		this.sex = sex;
	}
	Public String Getphoneno () {
		return phoneno;
	}
	public void Setphoneno (String phoneno) {
		This.phoneno = Phoneno;
	}
	public int getId () {
		return ID;
	}
	public void setId (int id) {
		this.id = ID;
	}
}
4, the entity class into MongoDB, and then according to the conditions obtained:

	@Autowired
	mongotemplate mongotemplate;
	
	@Test public
	void Mongosavegettest () throws jsonprocessingexception {
		String dbName = Mongotemplate.getdb (). GetName ();
		Logger.info ("DB name: {}", dbName);
		Assertthat (DbName, is ("test"));
		
		for (int. i=3;i<=25;i++) {person
			p = Persondao.getpersonbyid (i);
			if (p!=null) {
				mongotemplate.save (p);
			}
		}
		
		Criteria C = new criteria ();
		C.and ("id"). is (3);
		Person GOTP = Mongotemplate.findone (Query.query (c), person.class);
		Logger.debug ("p={}", Objectmapper.writevalueasstring (GOTP));
		Assertthat (Gotp.getfirstname (), Equalto ("seven"));
		
		set<string> collectionnames = Mongotemplate.getdb (). Getcollectionnames ();
		Logger.info ("colection names: {}", collectionnames);
		Assertthat (Collectionnames, Hasitem ("person"));
	
5, Statistics: Statistical sex for the "F" record, the number of people of the same surname

	@Test public
	void Mongoaggregationtest () throws jsonprocessingexception{
		criteria C = new criteria ();
		C.and ("Sex"). Is ("F");
		
		Aggregation Aggr = aggregation.newaggregation (
				aggregation.match (c),
	            aggregation.group ("LastName"). Count ( ). As ("Count")
	    );
		aggregationresults<basicdbobject> Aggrresult = mongotemplate.aggregate (Aggr, "person", basicdbobject.class);
		if (!aggrresult.getmappedresults (). IsEmpty ()) {for
			(Basicdbobject obj:aggrResult.getMappedResults ()) {
				Logger.info ("Count by First name: {}", objectmapper.writevalueasstring (obj));}}}	
	

Statistical results:

2016-10-27 18:02:11,911:info Main (myspringbootapplicationtests.java:111)-count by first name: {"_id": "Tian", "Count": 1}< c15/>2016-10-27 18:02:11,912:info Main (myspringbootapplicationtests.java:111)-count by first name: {"_id": "Li", "Count ": 19}






Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.