MongoDB operation: Insert ()

Source: Internet
Author: User

  1. @Override
  2. public boolean InSert (String dbName, String CollectionName, string[] keys,
  3. Object[] values) {
  4. DB db = null;
  5. Dbcollection dbcollection = null;
  6. Writeresult result = null;
  7. String resultstring = null;
  8. if (keys!=null && values!=null) {
  9. //keys and values are not empty when you can perform an insert operation
  10. if (keys.length! = values.length) {
  11. //keys and values are one by one corresponding relations, the number must be equal
  12. return false;
  13. }else{
  14. db = Mongoclient.getdb (dbName);
  15. Get DB Instance
  16. Dbcollection = Db.getcollection (CollectionName);
  17. Gets the specified collection collection in the database
  18. Basicdbobject insertobj = new Basicdbobject ();
  19. The basic object in//mongodb, which is the implementation of DBObject, inherits from Basicbsonobject
  20.    /*
  21.            *public class Basicdbobject extends Basicbsonobject implements DBObject
    */
  22. for (int i=0; i<keys.length; i++) {
  23. Build Add condition
  24. Insertobj.put (Keys[i], values[i]);
  25. //input k-v pair
  26. }
  27. try {
  28. result = Dbcollection.insert (insertobj);
  29. //Insert an object into the document collection
  30. resultstring = Result.geterror ();
  31. //write results Writeresult passed to resultstring for easy display
  32. } catch (Exception e) {
  33. Todo:handle exception
  34. E.printstacktrace ();
  35. }finally{
  36. if (null! = db) {
  37. //If the database is not empty, it means that the data has been inserted (the database was originally initialized to null)
  38. Db.requestdone ();
  39. Close the DB after the request ends (that is, stop continuing with the "request" operation)
  40. }
  41. }
  42. Return (resultstring! = null)? False:true;
  43. }
  44. }
  45. return false;
  46. }

MongoDB operation: Insert ()

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.