MongoDB Summary 2-java version of Helloworld-crud example

Source: Internet
Author: User
Tags findone object object print object

2013, the crud is too simple to write, today on the original basis, slightly improved under, with more syntax, such as sorting sort, in statements and so on.

Refer to the "MongoDB authoritative guide-1th Edition-HD", upload to csdn download channel, free points download.


The code is clear enough to explain too much.


Package Mongodb;import Java.net.unknownhostexception;import Java.util.date;import com.mongodb.basicdblist;import Com.mongodb.basicdbobject;import Com.mongodb.commandresult;import Com.mongodb.db;import com.mongodb.DBCollection; Import Com.mongodb.dbcursor;import com.mongodb.dbobject;import Com.mongodb.mongo;import com.mongodb.WriteResult;/* * * Mongodb-crud Demo. * * */public class Mongodbdemo {///////////////database address constant//////////////////////** * Database address */public static final String DEF Ault_host = "localhost";//localhost/** * Port number */public static final int default_port = 27017;////////////////database name and set constant// * * Database name */public static final String db_blog = "BLOG";/** * Collection name */public static final string Db_blog_c Ollection = "article";///////////////article article property name constant//////////////////////** * Title */public static final String title = " Title ";/** * content */public static final string content =" Content ";/** * Author */public static final string AUTHOR =" AUTHOR "; * * Date */public static finAl string date = "Date";p ublic static final String id = "id";p ublic static void Main (string[] args) throws Unknownhostexce ption {Mongo Mogo = new Mongo (Default_host, default_port);//Get database db Blogdb = Mogo.getdb (db_blog);D bcollection Articlecol lection = Blogdb.getcollection (db_blog_collection); Buildthreearticles (articlecollection);//Find and print the author as "FansUnion" Article Basicdbobject Searcharticlebyauthor = new Basicdbobject () searcharticlebyauthor.append (AUTHOR, "FansUnion"); Demofindbyfield (Articlecollection, Searcharticlebyauthor);d Emofindandsort (Articlecollection, Searcharticlebyauthor); Basicdbobject Searcharticlebyid = new Basicdbobject () searcharticlebyid.append (ID, 3L);d Emofindbyid ( Articlecollection, Searcharticlebyid);d Emofindspecialfield (articlecollection, Searcharticlebyid);d Emofindwithin ( articlecollection);d Emoupdatewithtwoway (articlecollection, Searcharticlebyauthor);d Emoremove (articleCollection) ;//The number of documents in the collection Long Count = Articlecollection.count ();p rintln ("delete the newly created 3 records, remaining count=" + count);//OffClosed connection mogo.close ();} Delete data private static void Demoremove (Dbcollection articlecollection) {//delete basicdbobject removecondition = new Basicdbobject (); Removecondition.append (AUTHOR, "fansunion"); Articlecollection.remove (removecondition); Basicdbobject removeCondition2 = new Basicdbobject (); Removecondition.append (TITLE, "HelloWorld");//Delete, And see if there is an error writeresult Writeresult = Articlecollection.remove (RemoveCondition2); Commandresult Commandresult = Writeresult.getlasterror ();p rintln ("View error information, find Err field is empty" + commandresult.tostring ()); Basicdbobject RemoveAll = new Basicdbobject (); Articlecollection.remove (RemoveAll);} 2 Ways to update objects private static void Demoupdatewithtwoway (Dbcollection articlecollection,basicdbobject Searcharticlebyauthor) {//The author of the article titled "HelloWorld" is modified to "Ray" println ("the author of the article titled HelloWorld, Modified to Ray, modified only AUTHOR1 fields");// Query condition: titled "HelloWorld" Basicdbobject updatecondition = new Basicdbobject (); Searcharticlebyauthor.append (title, " HelloWorld "); Basicdbobject newhelloworldarticle = new Basicdbobject (); newheLloworldarticle.append (AUTHOR, "Ray");//1th Way-Modify, modify only the specified field ("$set", "$inc" are modifiers)//update article set author= "Ray" where Title= ' HelloWorld ' dbobject updatesetvalue = new Basicdbobject ("$set", newhelloworldarticle); Articlecollection.update (Updatecondition, updatesetvalue);//Print the 1th time Modified "HelloWorld" article dbobject helloWordlArticle2 = Articlecollection.findone (updatecondition);p rint (helloWordlArticle2);//2nd Way-Modify//update article set author= "Ray", title=null,content=null,date=null//where title= ' HelloWorld ' println ("the author of the article titled HelloWorld, Modified to Ray, modified all fields"); Articlecollection.update (Updatecondition, newhelloworldarticle);D bobject hellowordlarticle = Articlecollection.findone (updatecondition)//Print the 2nd modified "HelloWorld" article print (hellowordlarticle); In statement for MongoDB private static void Demofindwithin (Dbcollection articlecollection) {//In Query println ("Find and print articles with IDs 1 and 2") ;//List List = Arrays.aslist;//long[] array= new long[]{1l,2l}; Basicdblist values = new Basicdblist (); Values.add (1); Values.add (2);D bobject inquery= new Basicdbobject ("$in", values);D bobject con = new Basicdbobject () con.put (ID, inquery);D bcursor Cursoridarray = Artic Lecollection.find (Con);p rintln ("number:" + cursoridarray.count ()), while (Cursoridarray.hasnext ()) {print ( Cursoridarray.next ());}} Query for a specific field private static void Demofindspecialfield (Dbcollection articlecollection,basicdbobject Searcharticlebyid) { println ("Find and print article 2 with ID 3, query the title field only"); Basicdbobject B = new Basicdbobject (); B.append (TITLE, 1);D bcursor Cursor3 = Articlecollection.find (Searcharticlebyid, b );p Rintln ("number:" + cursor3.count ()), while (Cursor3.hasnext ()) {print (Cursor3.next ());} Cursor3.close ();//In the absence of this line of code, the same program, appeared 1 times, the number is 4, look closely, found that their built-in ID is not the same//may be the last execution of the deletion, has not been completed? This place is a question, but it can't be reproduced}//. Find objects by ID private static Basicdbobject Demofindbyid (Dbcollection articlecollection, Basicdbobject Searcharticlebyid) {//Find and print an article with ID 3 println ("Find and print an article with ID 3");D bcursor Cursor2 = Articlecollection.find ( Searcharticlebyid);p rintln ("number:" + cursor2.count ()), while (Cursor2.hasnext ()) {print (cursor2.neXT ());} Cursor2.close (); return Searcharticlebyid;} Find objects and sort private static void Demofindandsort (Dbcollection articlecollection,basicdbobject searcharticlebyauthor) {/ /Find and print the author "fansunion" article, sorted by ID descending println ("Find and print the author Fansunion article, descending order, the ID of the query is 3,2,1"); Basicdbobject Orderbyiddesc = new Basicdbobject () Orderbyiddesc.append (ID,-1);D bcursor Cursoriddesc = Articlecollection.find (Searcharticlebyauthor). Sort (Orderbyiddesc); while (Cursoriddesc.hasnext ()) {print ( Cursoriddesc.next ());}} Find object based on field private static void Demofindbyfield (Dbcollection articlecollection,basicdbobject searcharticlebyauthor) { println ("Find and print an article for author Fansunion, query out the ID once for");D bcursor cursor = articlecollection.find (searcharticlebyauthor); while (Cursor.hasnext ()) {print (Cursor.next ());} Cursor.close ();//online and in the book for example, no close cursor, official JDK document "kills the current cursor on//the server."} Constructs 3 articles, the inserted ID order is 1,2,3private static void Buildthreearticles (Dbcollection articlecollection) {basicdbobject Article = Buildarticle ("A good socialist successor", "good study, day up","Fansunion", New Date (), 1L); Basicdbobject article2 = buildarticle ("Good capitalist Grave Digger", "work hard, always upward", "fansunion", New Date (), 2L); Basicdbobject article3 = buildarticle ("HelloWorld", "I am a MongoDb demo.", "Fansunion", New Date (), 3L);//Add several articles Articleco Llection.insert (article), Articlecollection.insert (Article2), Articlecollection.insert (article3);p rintln (" Insert the number of articles: "+ articlecollection.count ());} Print object private static void print (DBObject article) {//println ("-----------------------");p rintln ("Built-in ID:" + article.get ("_id")); println ("title:" + article.get (title));p rintln ("contents:" + article.get (content));p rintln ("" + Article.get (AUTHOR));p rintln ( "Date:" + article.get (date));p rintln ("ID:" + article.get (ID));p rintln ("-----------------------");} private static void println (Object object) {System.out.println (object);}  /** * Constructs 1 Article objects * * @param title * Title * @param content * Contents * @param author * author * @param Date * Dates * @return Article object */private static Basicdbobject buildarticLe (string title, String content,string Author, date date, Long ID) {basicdbobject article = new Basicdbobject (); Article.ap Pend (title, title), Article.append (content, content), Article.append (AUTHOR, AUTHOR), article.append (date, date); Article.append (ID, id); return article;}}

Code Execution results

Number of inserted posts: 3
Find and print an article written by the author Fansunion, once the ID of the query is
Built-in id:561baace3aea5b925fddc83c
Title: A good successor to socialism
Content: Good study, Day day up
Fansunion
Date: Mon Oct 2015 20:42:54 CST
Id:1
-----------------------
Built-in id:561baace3aea5b925fddc83d
Title: A good capitalist grave digger
Content: Work hard, always up
Fansunion
Date: Mon Oct 2015 20:42:54 CST
Id:2
-----------------------
Built-in id:561baace3aea5b925fddc83e
Title: HelloWorld
Content: I am a MongoDb demo.
Fansunion
Date: Mon Oct 2015 20:42:54 CST
Id:3
-----------------------
Find and print the author's fansunion articles, sorted in descending order, the ID of the query is 3,2,1
Built-in id:561baace3aea5b925fddc83e
Title: HelloWorld
Content: I am a MongoDb demo.
Fansunion
Date: Mon Oct 2015 20:42:54 CST
Id:3
-----------------------
Built-in id:561baace3aea5b925fddc83d
Title: A good capitalist grave digger
Content: Work hard, always up
Fansunion
Date: Mon Oct 2015 20:42:54 CST
Id:2
-----------------------
Built-in id:561baace3aea5b925fddc83c
Title: A good successor to socialism
Content: Good study, Day day up
Fansunion
Date: Mon Oct 2015 20:42:54 CST
Id:1
-----------------------
Find and print an article with ID 3
Number of items: 1
Built-in id:561baace3aea5b925fddc83e
Title: HelloWorld
Content: I am a MongoDb demo.
Fansunion
Date: Mon Oct 2015 20:42:54 CST
Id:3
-----------------------
Find and Print article 2 with ID 3, query only the title field
Number of items: 1
Built-in id:561baace3aea5b925fddc83e
Title: HelloWorld
Content: null
Null
Date: null
Id:null
-----------------------
Find and print an article with IDs 1 and 2
Number of items: 2
Built-in id:561baace3aea5b925fddc83c
Title: A good successor to socialism
Content: Good study, Day day up
Fansunion
Date: Mon Oct 2015 20:42:54 CST
Id:1
-----------------------
Built-in id:561baace3aea5b925fddc83d
Title: A good capitalist grave digger
Content: Work hard, always up
Fansunion
Date: Mon Oct 2015 20:42:54 CST
Id:2
-----------------------
Change the author of the article titled HelloWorld to Ray and modify only AUTHOR1 fields
Built-in id:561baace3aea5b925fddc83c
Title: A good successor to socialism
Content: Good study, Day day up
Ray
Date: Mon Oct 2015 20:42:54 CST
Id:1
-----------------------
The author of the article titled HelloWorld, Modified to Ray, changed all fields
Built-in id:561baace3aea5b925fddc83c
Title: null
Content: null
Ray
Date: null
Id:null
-----------------------
Check the error information and find that the Err field is empty {"serverused": "localhost/127.0.0.1:27017", "N": 1, "ConnectionID": 1, "err": null, "OK": 1 .0}
Deleted the newly created 3 records, the remaining count=0

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

MongoDB Summary 2-java version of Helloworld-crud example

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.