MongoDB JDBC Basic Use __mongodb

Source: Internet
Author: User
Tags documentation mongoclient mongodb mongodb query tojson
MongoDB Introductory Column

Http://blog.csdn.net/column/details/19681.html


Java Connection MongoDB
MongoDB provides a range of drivers for supporting various languages to connect MongoDB databases, including: java,python,c++,scala,php, complete driver list: https://docs.mongodb.com/manual/ Applications/drivers/index.html

This provides Java with Mongo-java-driver library support MONGO JDBC driver, which can be used as long as it is imported in Project dependencies: Org.mongodb:mongo-java-driver as in projects built using Gradle, the following import:

Compile ' org.mongodb:mongo-java-driver:3.6.3 '

Mongo JDBC Driver Documentation home: http://mongodb.github.io/mongo-java-driver/;
You can query the driver's detailed usage of the drive home page, the sample basic use, including: database connection, curd operation, use version: MongoDB 3.6,mongo-java-driver 3.6, different versions of the driver API by a number of differences, please query the driver document details;
Sample database Collection Testdb.blog Documentation example is as follows:
{
"_id": ObjectId ("5a8d519a07c9086ee823f15d"),
"title": "Mysql Overview",
"description": "Musql is a RDBMS",
"Author": "Assad",
"url": "http://blog.assad.article/233",
"Tages": ["MySQL", "RDBMS", "SQL"],
"Likes": 200
}


Database Connection 1) No authentication connection
Mongoclient mongoclient = new Mongoclient ("127.0.0.1", 27017);
Or use the MONGO URI
Mongoclient mongoclient = new Mongoclient (New Mongoclienturi ("mongodb://127.0.0.1:27017"));
2) Verify the connection
String user = "Assad"; User name
String database = "TestDB"; Database
char[] Password = "123". ToCharArray (); Password
Mongocredential credential = mongocredential.createcredential (User,database,password); Validating objects
Mongoclientoptions options = Mongoclientoptions.builder (). sslenabled (False). build (); Connection Action Object
Mongoclient mongoclient = new Mongoclient (New ServerAddress ("127.0.0.1", 27017), credential,options); Connection objects
Or use the MONGO URI
Mongoclient mongoclient = new Mongoclient (New Mongoclienturi ("mongodb://assad:123@127.0.0.1:27017/?authsource= Testdb&ssl=false "));
The authentication connection format for the MONGO URI is as follows: mongodb://username:password@host/?authsource=databasename&ssh=true;

Get Database & Collection
Get the specified Database object
Mongodatabase db = Mongoclient.getdatabase ("TestDB");
Gets the specified Collection object
mongocollection<document> blogs = db.getcollection ("blog");
Enumerate all database names
For (String DbName:blogs.listDatabaseNames ()
System.out.println (dbname);
Enumerates all collection names in the specified database
For (String colName:db.listCollectionNames ())
System.out.println (colname);

In the following example, the output for the document result is standard output using Log4j2;

Select query Operations
1) Query results traversalIn MongoDB JDBC, a Finditerable<document> object is generated for the query result that can be iterated by obtaining its iterator, and the object also provides a foreach method, passing in a block object, The results can be blocked iterations;
Database connection
Mongoclient mongoclient = new Mongoclient (New Mongoclienturi ("mongodb://assad:123@127.0.0.1:27017/?authsource= Testdb&ssl=false "));
mongocollection<document> blogs = mongoclient.getdatabase ("TestDB"). GetCollection ("blog");
Querying all documents, traversing output results
For (Document Document1:blogs.find ())
Log.debug (Document1.tojson ());
Querying all documents, traversing the results using the Walker
mongocursor<document> cursor = Blogs.find (). iterator ();
while (Cursor.hasnext ())
Log.debug (Cursor.next (). Tojson ());
Query all documents and use blocking callback method for all results
Blogs.find (). ForEach (block<document>) Document-> {
Log.debug (Document.tojson ());
});
Query all documents, Get Title field (string), likes field (Int32), tags field (array) in the resulting document
Blogs.find (). ForEach (block<document>) Document->{
String title = document.getstring ("title");
int likes = Document.getinteger ("likes");
list<string> tags = (list<string>) document.get ("tags");
Log.debug (title + "-" + Likes + "-" + tags);
});

2) Condition InquiryFor conditional query, we can construct a nested document object, produce a document chain similar to MongoDB query syntax, or use various static methods in Filters (such as eq,lte, etc.) to query functions, MongoDB JDBC has encapsulated most of the MONGODB query condition operators as functional calls;
Conditional query: Db.blog.find ({"Author": "Assad"})
Blogs.find (New Document ("author", "Assad")). ForEach ((block<document>) Document-> {
Log.debug (Document.tojson ());
});
Blogs.find (eq ("author", "Assad")). ForEach ((block<document>) Document-> {
Log.debug (Document.tojson ());
});
Conditional query: Db.blog.find ({"likes": {$gte: $, $lte: 500}})
Blogs.find (New document ("Likes", New Document ("$gte"). Append ("$lte", 500))
  . ForEach ((block<document>) Document-> {
Log.debug (Document.tojson ());
});
Blogs.find (GTE ("likes"), LTE ("likes", 500))
  . ForEach ((block<document>) Document-> {
Log.debug (Document.tojson ());
});
Conditional query: Db.blog.find ({"Author": "Assad", "title":/mongodb*/i})
Blogs.find (New document ("Author", "Assad"). Append ("title", New Document ("$regex",
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.