Java operations on mongodb

Source: Internet
Author: User
Tags findone mongodb update mongo shell

 

To use mongoDB, You need to import the following classes, not all of which are required.

Import com. mongodb. Mongo;

Import com. mongodb. DB;

Import com. mongodb. DBCollection;

Import com. mongodb. BasicDBObject;

Import com. mongodb. DBObject;

Import com. mongodb. DBCursor;

Import com. mongodb. ObjectId;

 

Class Conversion

After a class object is saved to mongoDB, use setObjectClass () to convert it back to the original class when it is retrieved from mongoDB.

Public class Tweet implements DBObject {

/*...*/

}

Tweet myTweet = new Tweet ();

MyTweet. put ("user", "bruce ");

MyTweet. put ("message", "fun ");

MyTweet. put ("date", new Date ());

Collection. insert (myTweet );

// Conversion

Collection. setObjectClass (Tweet );

Tweet myTweet = (Tweet) collection. findOne ();

 

Default ID

When no ID is set for the saved object, mongoDB sets an ID ("_ id") for the record by default ").

Of course, you can also set your own specified ID, such as: (execute db. users. save ({_ id: 1, name: 'Bruce '}) in mongoDB '});)

BasicDBObject bo = new BasicDBObject ();

Bo. put ('_ id', 1 );

Bo. put ('name', 'Bruce ');

Collection. insert (bo );

 

Permission

If you have mongoDB access permissions, true is returned. Otherwise, false is returned.

Boolean auth = db. authenticate (myUserName, myPassword );

 

View mongoDB database list

Mongo m = new Mongo ();

For (String s: m. getDatabaseNames ()){

System. out. println (s );

}

 

 

View all the table names in the current database. It is equivalent to executing show tables in mongoDB;

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

For (String s: colls ){

System. out. println (s );

}

 

View the index of a table

List <DBObject> list = coll. getIndexInfo ();

For (DBObject o: list ){

System. out. println (o );

}

 

Delete A Database

Mongo m = new Mongo ();

M. dropDatabase ("myDatabaseName ");

 

Create a mongoDB connection

Mongo m = new Mongo ("localhost", 27017 );

DB db = m. getDB ("myDatabaseName"); // The Database Name

DBCollection coll = db. getCollection ("myUsersTable"); // table name

 

# Querying data

Query the first record

DBObject firstDoc = coll. findOne ();

FindOne () returns a record, while find () returns the DBCursor cursor object.

 

Query all data

DBCursor cur = coll. find ();

While (cur. hasNext ()){

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

}

 

Query the number of records

Coll. find (). count ();

Coll. find (new BasicDBObject ("age", 26). count ();

 

Set conditional Query

BasicDBObject condition = new BasicDBObject ();

Condition. put ("name", "bruce ");

Condition. put ("age", 26 );

Coll. find (condition );

 

Query part of data blocks

DBCursor cursor = coll. find (). skip (0). limit (10 );

While (cursor. hasNext ()){

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

}

 

Comparison query (age> 50)

BasicDBObject condition = new BasicDBObject ();

Condition. put ("age", new BasicDBObject ("$ gt", 50 ));

Coll. find (condition );

Comparison operator

"$ Gt": greater

"$ Gte": greater than or equal

"$ Lt": less

"$ Lte": less than or equal

"$ In": Contains

// The following conditions query 20 <age <= 30

Condition. put ("age", new BasicDBObject ("$ gt", 20). append ("$ lte", 30 ));

 

# Insert data

Batch insert

List datas = new ArrayList ();

For (int I = 0; I <100; I ++ ){

BasicDBObject bo = new BasicDBObject ();

Bo. put ("name", "bruce ");

Bo. append ("age", I );

Datas. add (bo );

}

Coll. insert (datas );

 

Regular Expression

Query all name matches/joh? N/I records

Pattern pattern = Pattern. compile ("joh? N ", CASE_INSENSITIVE );

BasicDBObject query = new BasicDBObject ("name", pattern );

DBCursor cursor = coll. find (query );

 

 

How to Use mongoDb update

The key is in $ set, there are a lot of tests, addresses: http://www.mongodb.org/display/DOCS/Updating#Updating-%24inc

?

Update (BasicDBobject, BasicDBobject)

The first parameter is the search condition, the object to be modified, and the second parameter is the modification content. If the set parameter is not used, the original object is updated to the current object.

If $ set exists, the attribute is updated. If the attribute does not exist, the attribute is added. Other parameters are used in the same way.

?

?

 

DBCollection coll2 = db. getCollection (Config. SENDER_EMAIL_MESSAGE );

 

?

 

Coll2.update (

New BasicDBObject ("key", sender. get ("key ")),

New BasicDBObject ("$ set", new BasicDBObject (

"FinallyUseTime", Math. floor (System

. CurrentTimeMillis ()

/Config. SEND_FREQUENCY ))));

 

 

?

 

------------------------------------------------

 

To make it easier to reference the completed content here

 

MongoDB supports atomic, in-place updates as well as more traditional updates for replacing an entire document.

 

* Update ()

* Save () in the mongo shell

* Modifier Operations

+ $ Inc

+ $ Set

+ $ Unset

+ $ Push

+ $ PushAll

+ $ AddToSet

+ $ Pop

+ $ Pull

+ $ PullAll

+ $ Rename

O The $ positional operator

O Upserts with Modifiers

O Pushing a Unique Value

* Checking the Outcome of an Update Request

* Notes

O Object Padding

O Blocking

* See Also

 

Update ()

 

Update () replaces the document matching criteria entirely with objNew. If you only want to modify some fields, you shocould use the atomic modifiers below.

 

Here's the MongoDB shell syntax for update ():

 

Db. collection. update (criteria, objNew, upsert, multi)

 

Arguments:

 

* Criteria-query which selects the record to update;

* ObjNew-updated object or $ operators (e.g., $ inc) which manipulate the object

* Upsert-if this shoshould be an "upsert"; that is, if the record does not exist, insert it

* Multi-if all variables ents matching criteria shoshould be updated

 

 

If you are coming from SQL, be aware that by default, update () only modifies the first matched object. If you want to modify all matched objects you need to use the multi flag

Save () in the mongo shell

 

The save () command in the mongo shell provides a shorthand syntax to perform a single object update with upsert:

 

// X is some JSON style object

Db. mycollection. save (x); // updates if exists; inserts if new

 

Save () does an upsert if x has an _ id field and an insert if it does not. Thus, normally, you will not need to explicitly request upserts, just use save ().

 

Upsert means "update if present; insert if missing ".

 

MyColl. update ({_ id: X}, {_ id: X, name: "Joe", age: 20}, true );

 

Modifier Operations

 

Modifier operations are highly-efficient and useful when updating existing values; for instance, they're great for incrementing a number.

 

So, while a conventional implementation does work:

 

Var j = myColl. findOne ({name: "Joe "});

J. n ++;

MyColl. save (j );

 

A modifier update has the advantages of avoiding the latency involved in querying and returning the object. The modifier update also features operation atomicity and very little network data transfer.

 

To perform an atomic update, simply specify any of the special update operators (which always start with a' $ 'character) with a relevant update document:

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.