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