Java Operations MongoDB sample sharing _java

Source: Internet
Author: User
Tags array example findone mongoclient mongodb

Copy Code code as follows:

Package Mymaven;

Import java.net.UnknownHostException;
Import Java.util.Set;

Import Com.mongodb.BasicDBObject;
Import Com.mongodb.DB;
Import com.mongodb.DBCollection;
Import Com.mongodb.DBCursor;
Import Com.mongodb.DBObject;
Import Com.mongodb.Mongo;
Import com.mongodb.MongoException;

public class Test {
public static void Main (string[] args) throws Unknownhostexception, Mongoexception {
Mongo Mongo = new Mongo ("172.27.9.104", 27017); Connecting to a database
DB db = Mongo.getdb ("Mytestdb"); Database
set<string> cols = Db.getcollectionnames (); Get all the collections in the database (similar to getting tables in the relational database)

Print out the collection in the database, which should be null
for (String S:cols) {
System.out.println (s);
}

Dbcollection collection = Db.getcollection ("Mytestcoll"); Create a Collection
Collection.drop (); Delete collection, automatically rebuild when inserting data
Basicdbobject obj = new Basicdbobject (); Initializes a base DB object, which is the DB object that is inserted into the database

Obj.put ("from", "blog.ithomer.net"); Put several key value pairs
Obj.put ("To", "forum.ithomer.net");
Obj.put ("Subject", "ithomer.net");
Collection.insert (obj); Insert Object

DBObject dbobj = Collection.findone (); View a record, FindOne () =find (). limit (1);
System.out.println (Dbobj); Print out the data that you just inserted

Insert data for 10 {ranking:i}
for (int i = 0; i < i++) {
Collection.insert (New Basicdbobject (). Append ("ranking", I));
}
System.out.println ("Count:" + collection.getcount ()); Print the total number of data in a collection


dbcursor cursor = Collection.find (); Then we use this cursor to traverse the collection
while (Cursor.hasnext ()) {
System.out.println (Cursor.next ());
}
Simple conditional query, query ranking 1 records
Basicdbobject query = new Basicdbobject ();
Query.put ("ranking", 1);
cursor = collection.find (query);
System.out.println ("collection find ({\" ranking\ ": 1}):");
while (Cursor.hasnext ()) {
System.out.println (Cursor.next ());
}

Complex conditional query with a query ranking greater than or equal to 5 less than 9 records
query = new Basicdbobject ();
Query.put ("ranking", New Basicdbobject ("$gte", 5). Append ("$lt", 9));
cursor = collection.find (query);
System.out.println ("collection find ({\ ranking\": [5-9)}): ");
while (Cursor.hasnext ()) {
System.out.println (Cursor.next ());
}

Mongo.dropdatabase ("Mytestdb"); Finally, delete our test database
}
}

Run Result:

Copy Code code as follows:

Mytestcoll
System.indexes
{"_id": {"$oid": "52c62ed8e4b0f4de3dd10107"}, "from": "Blog.ithomer.net", "to": "Forum.ithomer.net", "Subject": "Ithomer.net"}
Count:11
{"_id": {"$oid": "52c62ed8e4b0f4de3dd10107"}, "from": "Blog.ithomer.net", "to": "Forum.ithomer.net", "Subject": "Ithomer.net"}
{"_id": {"$oid": "52c62ed8e4b0f4de3dd10108"}, "ranking": 0}
{"_id": {"$oid": "52c62ed8e4b0f4de3dd10109"}, "ranking": 1}
{"_id": {"$oid": "52c62ed8e4b0f4de3dd1010a"}, "ranking": 2}
{"_id": {"$oid": "52c62ed8e4b0f4de3dd1010b"}, "Ranking": 3}
{"_id": {"$oid": "52c62ed8e4b0f4de3dd1010c"}, "ranking": 4}
{"_id": {"$oid": "52c62ed8e4b0f4de3dd1010d"}, "ranking": 5}
{"_id": {"$oid": "52c62ed8e4b0f4de3dd1010e"}, "ranking": 6}
{"_id": {"$oid": "52c62ed8e4b0f4de3dd1010f"}, "ranking": 7}
{"_id": {"$oid": "52c62ed8e4b0f4de3dd10110"}, "ranking": 8}
{"_id": {"$oid": "52c62ed8e4b0f4de3dd10111"}, "ranking": 9}
Collection find ({"Ranking": 1}):
{"_id": {"$oid": "52c62ed8e4b0f4de3dd10109"}, "ranking": 1}
Collection find ({"ranking": [5-9)}):
{"_id": {"$oid": "52c62ed8e4b0f4de3dd1010d"}, "ranking": 5}
{"_id": {"$oid": "52c62ed8e4b0f4de3dd1010e"}, "ranking": 6}
{"_id": {"$oid": "52c62ed8e4b0f4de3dd1010f"}, "ranking": 7}
{"_id": {"$oid": "52c62ed8e4b0f4de3dd10110"}, "ranking": 8}

MongoDB Array Example:

Copy Code code as follows:

@SuppressWarnings ("Unchecked")
public static void Loadmediatags (List<mediaentity> mediaentitylist) {
Mediaentitylist.clear ();

try {
Mongo Mongo = new Mongo (Cosinecluster.gmongo_host, Cosinecluster.gmongo_port);
DB db = Mongo.getdb (cosinecluster.gmongo_db);
Dbcollection collection = Db.getcollection (Cosinecluster.gmongo_coll_media);

dbcursor cursor = Collection.find ();
int index = 0;
Long starttime = System.currenttimemillis ();
while (Cursor.hasnext ()) {
Basicdbobject obj = (basicdbobject) cursor.next ();

Long id = obj.getlong ("_id");
Arraylist<string> taglist = (arraylist<string>) obj.get ("tag"); Tag
Arraylist<string> keywordlist = (arraylist<string>) obj.get ("keyword"); Keyword
Arraylist<integer> copyrightlist = (arraylist<integer>) obj.get ("copyright"); Copyright


Mediaentity mediaentity = new mediaentity ();

Mediaentity.setid (ID);

Tag
for (int j=0; j<taglist.size (); j + +) {
Mediaentity.addtag (Taglist.get (j));
int tagid = Gettagint (Taglist.get (j));
Mediaentity.addtag (TagID);
}

Actors
Arraylist<dbobject> actorsobjlist = (arraylist<dbobject>) obj.get ("actors"); Actors
for (int j=0; j<actorsobjlist.size (); j + +) {
Mediaentity.addactor ((String) Actorsobjlist.get (j). Get ("name");
int actorid = Getactorint ((String) Actorsobjlist.get (j). Get ("name");
Mediaentity.addactor (Actorid);
}

Director
Arraylist<dbobject> directorobjlist = (arraylist<dbobject>) obj.get ("director"); Director
for (int j=0; j<directorobjlist.size (); j + +) {
Mediaentity.adddirector ((String) Directorobjlist.get (j). Get ("name");
int directorid = Getdirectorint ((String) Directorobjlist.get (j). Get ("name");
Mediaentity.adddirector (Directorid);
}

Keyword
for (int j=0; j<keywordlist.size (); j + +) {
Mediaentity.addkeyword (Keywordlist.get (j));
int keywordid = Getkeywordint (Keywordlist.get (j));
Mediaentity.addkeyword (Keywordid);
}

Copyright
for (int j=0; j<copyrightlist.size (); j + +) {
Mediaentity.addcopyright (Copyrightlist.get (j));
}

Mediaentitylist.add (mediaentity);

index++;
if (Index > 100) {
Break
}
SYSTEM.OUT.PRINTLN (index + "---mediaentity:" + mediaentity.tostring ());
}
Long costtime = System.currenttimemillis ()-starttime;
SYSTEM.OUT.PRINTLN ("load data Costtime = + index +"; Costtime = "+ costtime/1000f);

catch (Exception e) {
E.printstacktrace ();
}
}

public static int Gettagint (String tag) {
int tagintid =-1;

try {
Mongoclient MONGO = new Mongoclient (Cosinecluster.gmongo_host, Cosinecluster.gmongo_port);
DB db = Mongo.getdb (cosinecluster.gmongo_db);
Dbcollection tagmapcollection = db.getcollection ("Recommend_tag_map");

dbcursor cursor = tagmapcollection.find (new Basicdbobject ("name", tag);
if (cursor = NULL | | Cursor.toarray (). Size () <= 0) {//Handle mapping keywords less than 2 or N, below
return tagintid;
}
DBObject obj = Cursor.toarray (). get (0);


String name = tag;
Tagintid = (Integer) obj.get ("id");
int num = (Integer) obj.get ("num");

Mongo.close ();
catch (Unknownhostexception e) {
E.printstacktrace ();
}

return tagintid;
}

public static int Getactorint (String actor) {
int actorintid =-1;
try {
Mongoclient MONGO = new Mongoclient (Cosinecluster.gmongo_host, Cosinecluster.gmongo_port);
DB db = Mongo.getdb (cosinecluster.gmongo_db);
Dbcollection tagmapcollection = db.getcollection ("Recommend_actor_map");

dbcursor cursor = tagmapcollection.find (new Basicdbobject ("name", actor));
if (cursor = NULL | | Cursor.toarray (). Size () <= 0) {
return actorintid;
}
DBObject obj = Cursor.toarray (). get (0);

String name = actor;
Actorintid = (Integer) obj.get ("id");
int num = (Integer) obj.get ("num");

Mongo.close ();
catch (Unknownhostexception e) {
E.printstacktrace ();
}

return actorintid;
}

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.