Analysis of MongoDB Java operation syntax

Keywords: MongoDB Database Java JSON

;

The connection between Java and mongodb

1. Single mongodb

Mongo mg = new Mongo();//The default connection port of 127.0.0.1 is 27017

Mongo mg = new Mongo(ip);//You can specify that the ip port defaults to 27017

Mongo mg = new Mongo(ip,port);//ip and port can also be specified

2. Connect two mongodb s

//ip is the host ip address, port is the port number, and dataBaseName is the database name

DBAddress left = new DBAddress("ip:port/dataBaseName");

DBAddress right = new DBAddress("ip:port/dataBaseName ");

//If one mongodb has problems, it will automatically connect to another

Mongo mongo = new Mongo(left, right);

3. Connect multiple mongodb s

List<ServerAddress> mongoHostList = new ArrayList<ServerAddress>();

mongoHostList.add(new ServerAddress("ip",port));

mongoHostList.add(new ServerAddress("ip",port));

mongoHostList.add(new ServerAddress("ip",port));

Mongo mg = new Mongo(mongoHostList);

Java gets the database name of mongodb

1. Get the db (database) of mongodb

//dataBaseName is equivalent to the database name in the relational database. If there is no

//The database name will not report an error. By default, mongodb will create the database name, which is empty.

DB db = mg.getDB(dataBaseName);

Note: mongodb is case sensitive. Be sure to pay attention to it in the program

2. db security authentication of mongodb

//The java code of security authentication returns true to indicate that it has passed, and false to indicate that it cannot operate if it has failed

db.authenticate("userName", "password".toCharArray());

if(db.authenticate("admin", "123".toCharArray())){

    System.out.println("Connect mongodb Success...");

} else{

    System.out.println("Connect mongodb fail...");

}

Java crud the collection of mongodb

1. Get the collection (table) of db in mongodb

//The parameter tableName is equivalent to the table name in the relational database,

//If the tableName does not exist in mongodb, the tableName will be created by default, which is empty 

DBCollection users = db.getCollection(tableName);

//Column the list of collections issued, relative to the table object

Set<String> colls = db.getCollectionNames();

for(String s : colls){

}
// Get a single collection

DBCollection con = db.getCollection("users");

2. collection self growing primary key of db in mongodb

  Mongodb As in the traditional relational database, there is a primary key(_id)Concept, used to uniquely identify them. When users go to collection When inserting a new record in, if no_id Property, then mongodb Will automatically generate a ObjectId Value of type, saved as_id Value of.

  _id The value of can be of any type except array. In practical application, the user is encouraged to define_id It's worth it, but make sure it's unique.

  //In the traditional database, an increasing sequence is usually used to provide the primary key. In Mongodb, ObjectId is used instead. We can get the primary key through the following methods.

public class Tools {

/**

 * Realizing the function of mongodb primary key self growth

 * @param users

 * @param tableName

 * @return

 */

public static long getNext(DBCollection users,String tableName){

long incId = 0;

try {

  DBObject ret = users.findAndModify(

  new BasicDBObject("_id", tableName), null, null, false,

  new BasicDBObject("$inc", new BasicDBObject("next", 1)),

  true, true);

  incId = Long.valueOf(ret.get("next").toString());

} catch (Exception e) {

  e.printStackTrace();

}

  return incId;

}

}

3.java inserts collection

DB db = m.getDB("testdb");

DBCollection con = db.getCollection("users");

//Normal addition

BasicDBObject doc = new BasicDBObject();

doc.put("name", "MongoDB");

doc.put("type", "database");

doc.put("count", 1);

BasicDBObject info = new BasicDBObject();

info.put("x", 203);

info.put("y", 102);

doc.put("info", info);

con.insert(doc); //Insert Object

//Special addition

// Add multiple special data (mode free)

for(int i = 1; i <=20; i++){

con.insert(new BasicDBObject().append("i", i));

}
 
//Add JSON data

DBObject user_json = (DBObject)JSON.parse("{'user':[{'name':'AAA', 'age':'18'},{'name':'BBB', 'age':'19'}]}");

con.insert(user_json);

//Add JAVA object

// Add java object to serialize Serializable interface

UserInfo userinfo = new UserInfo("User a AA", 1);

User user = new User(1, "123", userinfo);

ByteArrayOutputStream os = new ByteArrayOutputStream(); 

ObjectOutputStream out = new ObjectOutputStream(os);  

out.writeObject(user);

os.close(); out.close();

con.insert(MonGoUtil.insertObject("user_info",os.toByteArray()));
 
//Add LIST-JAVA object set

List<UserInfo> list = new ArrayList<UserInfo>();

list.add(new UserInfo("List1", 1));

list.add(new UserInfo("List2", 2));

list.add(new UserInfo("List3", 3));

ByteArrayOutputStream os = new ByteArrayOutputStream(); 

ObjectOutputStream out = new ObjectOutputStream(os);  

out.writeObject(list);

os.close(); out.close();

con.insert(MonGoUtil.insertObject("lists",os.toByteArray()));

4.java query on collection

/** Output the acquired document**/

public static void showDBCursor(DBCursor cur){

  while(cur.hasNext()){

  System.out.println(cur.next());

  }

  System.out.println();

}

 //Advanced query

//Query with id 30000 returns cust id, and mongodb query returns the value of primary key

System.out.println(users.findOne(new BasicDBObject("_id",30000),new BasicDBObject("cust_Id",true)));

findAndRemove() query_id=30000 And delete

users.findAndRemove(new BasicDBObject("_id", 30000));

findAndModify introduce

users.findAndModify(

        new BasicDBObject("_id", 28), //Query data with ﹐ id=28

        new BasicDBObject("cust_Id", true), //Query cust? ID attribute

        new BasicDBObject("notice_Id", true), //Sort by notice? ID

        false, //Whether to delete the queried records. true means to delete

        new BasicDBObject("province_Id", "100"), //Change the value of "provision" ID to 100

        true, //Whether to return a new record true, false not

        true  //If it is not queried whether the data is inserted into collection true, false will not be entered

));

//Query all data

//List all documents

BasicDBObject query = new BasicDBObject();

System.out.println("list"+ con.getName() +"aggregate(surface)All documents for...");

showDBCursor(con.find());

//Querying JAVA objects

String key = "user_info";

BasicDBObject query = new BasicDBObject();

query.put(key, new BasicDBObject("$exists", true));

byte[] b = (byte[])con.findOne(query).get(key);

InputStream inputStream  = new ByteArrayInputStream(b); 

ObjectInputStream in = new ObjectInputStream(inputStream);  

User users = (User) in.readObject();

System.out.println("User object_json: " + JSONArray.fromObject(users));

 //Single criteria query (number)

BasicDBObject query = new BasicDBObject();

query.put("i", 11);

showDBCursor(con.find(query));

 //Single condition query (string)

BasicDBObject query = new BasicDBObject();

query.put("name", "MongoDB");

showDBCursor(con.find(query));

 $ne Not equal to query

BasicDBObject query = new BasicDBObject();

query.put("name", new BasicDBObject("$ne", "MongoDB"));

showDBCursor(con.find(query));

 //Query by column name

System.out.println("Query yes'type'Data for field..."); // false means no

BasicDBObject query = new BasicDBObject();

query.put("type", new BasicDBObject("$exists", true)); // false

showDBCursor(con.find(query));

 //Single field and query

System.out.println("Single field and Use of conditions, i>=2 and i<5 ,i:[2,5)...");

BasicDBObject query = new BasicDBObject();

query.put("i", new BasicDBObject("$gte", 2).append("$lt", 5));

showDBCursor(con.find(query));

 //Multi field and query

BasicDBObject query = new BasicDBObject();();

query.put("name", "MongoDB");

query.put("type", "database");

System.out.println(con.findOne(query));

showDBCursor(con.find(query));

 //Single field or query

System.out.println("Single field or Use of conditions, i<2 or i>=18...");

BasicDBList values = new BasicDBList();  

values.add(new BasicDBObject("i", new BasicDBObject("$gte", 18)));  

values.add(new BasicDBObject("i", new BasicDBObject("$lt", 2)));

BasicDBObject query = new BasicDBObject();();

query.put("$or", values);

showDBCursor(con.find(query));

//Multi field or query

// "Use of multi field or condition, name:'MongoDB' or x:'203'..."

BasicDBList values = new BasicDBList();  ();

values.add(new BasicDBObject("name", "MongoDB"));  

values.add(new BasicDBObject("x", 203));

BasicDBObject query = new BasicDBObject();();

query.put("$or", values);

showDBCursor(con.find(query));

$in query

System.out.println("in Use of conditions $in...");

BasicDBList values = new BasicDBList();  ();

for (int i = 1; i <=10; i++) {

  values.add(i);

}

BasicDBObject query = new BasicDBObject();();

query.put("i", new BasicDBObject("$in", values));

showDBCursor(con.find(query));

Order By Sort query

System.out.println("sort[1=asc,-1=desc]...");

showDBCursor(con.find(query).sort(new BasicDBObject("i", -1)));

//Paging query

// "Use of paging query, total data volume:" + con.find(query).count()

con.find(query).limit(1); // Take only the first data

con.find(query).skip(1).limit(1); // Take 1 piece of data from 1, and subscript from 0

con.find(query).sort(new BasicDBObject("i", -1)).skip(0).limit(5);  // 5 data after DESC

//findAndRemove() method, delete the queried data and the deleted result set

con.findAndRemove(new BasicDBObject("i", 1));

showDBCursor(con.find(query));

con.findAndRemove(new BasicDBObject("i", new BasicDBObject("$in",   values))); //[Note: multiple values are invalid]

showDBCursor(con.find(query));

 (not)  OR  (not in)query

System.out.println("not,not in Use of conditions $not");

BasicDBObject query = new BasicDBObject();();

query.put("i", new BasicDBObject("$not", new BasicDBObject("$in", values)));

showDBCursor(con.find(query));

 Like Fuzzy query

System.out.println("like Use of queries...");

BasicDBObject query = new BasicDBObject();();

query.put("type", MonGoUtil.getLikeStr("a"));

showDBCursor(con.find(query));

 //Query by field type

System.out.println("Query by data type, character type...");

BasicDBObject query = new BasicDBObject();();

query.put("name", new BasicDBObject("$type", 2)); //byte

showDBCursor(con.find(query));

System.out.println("Query by data type, integer...");

BasicDBObject query = new BasicDBObject();();

query.put("i", new BasicDBObject("$type", 16));

showDBCursor(con.find(query));

  //Return some fields of the query

//"Query some fields of data. 1 means only this field is returned, 0 means fields other than this field"

con.find(new BasicDBObject("name", MonGoUtil.getLikeStr("b")), new BasicDBObject("name", 1));

5.java update of collection

//Query the record with id 300, and update cust to 6533615. Pay attention to case and data / / type. The return value is int, indicating the number of records affected

//You can use users.findone (New basicdbobject ("_id, 300)); to view the record / / only two fields are returned, namely, _id and cust_id. all other fields are deleted.

users.update(new BasicDBObject("_id",300), new BasicDBObject ("cust_Id","6533615")).getN();

// Parameter 3 indicates whether to add or not the database does not exist (default false), and parameter 4 indicates whether to modify more than one (false only modifies one)

con.update(new BasicDBObject("name", "MongoDB"), 

new BasicDBObject("$set", new BasicDBObject("type", "Modified type"))).getN();

con.update(new BasicDBObject("name", "MongoDBs"), 

new BasicDBObject("$set", new BasicDBObject("type", "Modified type")), true, true).getN();

6.java delete collection

/remove cust_Id Is 6533615. Pay attention to using remove Method does not free disk space,

//mongodb is only marked in collection and is not being deleted.

users.remove(new BasicDBObject("cust_Id","6533615")).getN();

//Remove data with ID > = 1

users.remove(newBasicDBObject("_id",new BasicDBObject("$gte",1))).getN();

//Remove the entire collection and drop does not free disk space

users.drop();

// Delete documents (data) according to conditions

BasicDBList rls = new BasicDBList();

for (int i = 11; i <= 20; i++) {

  rls.add(i);

}

query.put("i", new BasicDBObject("$in", rls));

con.remove(query);

7. Read Binary Data type data in mongodb

 Binary binary = (Binary) doc.get("Data");

 byte[] data=binary.getData();

Life goes on, struggle goes on

Posted by aliahmad on Sat, 02 May 2020 22:55:28 -0700