Java simple manipulation of the MongoDB database

Source: Internet
Author: User

Preparatory work:

Download the Mongodriver.jar package (HTTPS://OSS.SONATYPE.ORG/CONTENT/REPOSITORIES/RELEASES/ORG/MONGODB/MONGODB-DRIVER/3.6.1/)

Code implementation:

try {
Instantiating a MONGO object, connecting 27017 ports
Mongo Mongo = new Mongo ("localhost", 27017);
Connect a database named Yourdb, if the database does not exist, MongoDB will automatically establish
DB db = Mongo.getdb ("test");
Get collection from MongoDB, database named "Yourdb"
A collection of data named Yourcolleection is obtained from MongoDB, and if the data collection does not exist, MongoDB creates a new
Dbcollection collection = Db.getcollection ("Test1");
Use the Basicdbobject object to create a MongoDB document and give the assignment.
Basicdbobject document = new Basicdbobject ();
Document.put ("id", 1001);
Document.put ("msg", "Hello World MongoDB in Java");
Save the newly created document to the collection
Collection.insert (document);
Create the document to query
Basicdbobject searchQuery = new Basicdbobject ();
Searchquery.put ("name", "Chen");
Find document using Collection's Find method
Dbcursor cursor =collection.find (searchQuery);
Loop output Results
while (Cursor.hasnext ()) {
System.out.println (Cursor.next ());
}
System.out.println ("Hello World");
} catch (Unknownhostexception e) {
E.printstacktrace ();
} catch (Mongoexception e) {
E.printstacktrace ();
}

Java simple manipulation of the MongoDB database

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.