Package Com.moonlit.example;import Com.mongodb.basicdbobject;import com.mongodb.bulkwriteoperation;import Com.mongodb.bulkwriteresult;import Com.mongodb.db;import Com.mongodb.dbcollection;import com.mongodb.DBCursor; Import Com.mongodb.dbobject;import com.mongodb.MongoClient; Publicclass Mongodbtest { Publicstatic void Main (String[]args) {mongoclient mongoclient=new Mongoclient (); DB DB=mongoclient.getdb ("MyDB"); Dbcollection Coll=db.getcollection ("testcollection"); // Inserta document Basicdbobject Doc=New Basicdbobject ("name", "MongoDB"). Append ("type", "Database"). Append ("Count",1). Append ("Info", New Basicdbobject ("X",123). Append ("Y",456)); Coll.Insert(DOC); //Find the first documentinchA collection DBObject myDoc=Coll.findone (); System.out.println (MYDOC); //Adding multiple documents for(intI= 1; I<= -; I++) {Coll.Insert(New Basicdbobject ("I", I)); } //Counting documentsincha collection System.out.println (Coll.getcount ()); //Using acursor toGet AllCollection Dbcursorcursor =Coll.find (); try { while(cursor. Hasnext ()) System.out.println (cursor.Next()); } finally {cursor.Close(); } //Get a SingleDocument witha guery basicdbobject query=New Basicdbobject ("I", at); cursor =coll.find (query); try { while(cursor. Hasnext ()) System.out.println (cursor.Next()); } finally {cursor.Close(); } Query=New Basicdbobject ("J", New Basicdbobject ("$ne", the) . Append ("I", New Basicdbobject ("$gt", -)); cursor =coll.find (query); try { while(cursor. Hasnext ()) System.out.println (cursor.Next()); } finally {cursor.Close(); } Query=New Basicdbobject ("I", New Basicdbobject ("$ne", the). Append ("$gt", -)); cursor =coll.find (query); try { while(cursor. Hasnext ()) System.out.println (cursor.Next()); } finally {cursor.Close(); }// // Delete All // cursor =Coll.find ();//try {// while(cursor. Hasnext ())//Coll.remove (cursor.Next());//} finally {// cursor.Close();// }// // // Count//System.out.println (Coll.getcount ()); //Bulkwriteoperation Builder=coll.initializeorderedbulkoperation ();//Builder.Insert(New Basicdbobject ("_id",1));//Builder.Insert(New Basicdbobject ("_id",2));//Builder.Insert(New Basicdbobject ("_id",3)); //Builder.find (New Basicdbobject ("_id",1). Updateone (New Basicdbobject ("$Set", New Basicdbobject (" X ",123)));//Builder.find (New Basicdbobject ("_id",2) . Remove ();//Builder.find (New Basicdbobject ("_id",3). Replaceone (New Basicdbobject ("_id"),3). Append ("X",4)); //Bulkwriteresult result=Builder.Execute(); }}
Java Connection MongoDB Sample