MongoDB and Java operations

Source: Internet
Author: User
Tags findone modifiers 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 = 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:

DB. People. Update ({name: "Joe" },{$ Inc: {n: 1 }});

The preceding example says, "find the first document where 'name' is 'job' and then increment 'n' by one ."

While not shown in the examples, most modifier operators will accept multiple field/value pairs when one wishes to modify multiple fields. for example, the following Operation wowould set X to 1 and Y to 2:

{$ Set: {X: 1, Y: 2 }}

Also, multiple operators are valid too:

{$ Set: {X: 1}, $ Inc: {y: 1 }}

$ Inc

{$ Inc: {field: Value }}

Increments field by the number value if field is present in the object, otherwise sets field to the number value.
$ Set

{$ Set: {field: Value }}

Sets field to value. All datatypes are supported with $ set.
$ Unset

{$ Unset: {field: 1 }}

Deletes a given field. v1.3 +
$ Push

{$ Push: {field: Value }}

Appends value to field, if field is an existing array, otherwise sets field to the array [value] If field is not present. iffield is present but is not an array, an error condition is raised.
$ Pushall

{$ Pushall: {field: value_array }}

Appends each value in value_array to field, if field is an existing array, otherwise sets field to the array value_arrayif field is not present. if field is present but is not an array, an error condition is raised.
$ Addtoset

{$ Addtoset: {field: Value }}

Adds value to the array only if its not in the array already, if field is an existing array, otherwise sets field to the arrayvalue if field is not present. if field is present but is not an array, an error condition is raised.

To add multicast valuest. Update

{$ Addtoset: {A :{$ each: [3, 5, 6]}

$ Pop

{$ POP: {field: 1 }}

Removes the last element in an array (added in 1.1)

{$ POP: {field:-1 }}

Removes the first element in an array (added in 1.1) |
$ Pull

{$ Pull: {field: _ value }}

Removes all occurrences of value from field, if field is an array. If field is present but is not an array, an error condition is raised.

In addition to matching an exact value you can also use expressions ($ pull is special in this way ):

{$ Pull: {field: {field2: Value }}} removes array elements with field2 matching Value

{$ Pull: {field :{$ GT: 3 }} removes array elements greater than 3

{$ Pull: {field :{< match-criteria >}} removes array elements meeting match criteria

Because of this feature, to use the embedded doc as a match criteria, you cannot do exact matches on array elements.
$ Pullall

{$ Pullall: {field: value_array }}

Removes all occurrences of each value in value_array from field, if field is an array. If field is present but is not an array, an error condition is raised.
$ Rename

Version 1.7.2 + only.

{$ Rename: {old_field_name: new_field_name }}

Renames the field with name 'Old _ field_name 'to 'new _ field_name'. does not expand arrays to find a match for 'old _ field_name '.

The $ positional Operator

Version 1.3.4 + only.

The $ operator (by itself) means "position of the matched array item in the query". Use this to find an array member and then manipulate it. For example:

> T. Find ()
{"_ Id": objectid ("4b97e62bf1d8c7152c9ccb74"), "title": "ABC ",
"Comments": [{"by": "Joe", "votes": 3 },{ "by": "Jane", "votes": 7}]}

> T. Update ({'comments. by': 'job'}, {$ Inc: {'comments. $. Votes ': 1 }}, false, true)

> T. Find ()
{"_ Id": objectid ("4b97e62bf1d8c7152c9ccb74"), "title": "ABC ",
"Comments": [{"by": "Joe", "votes": 4 },{ "by": "Jane", "votes": 7}]}

Currently the $ operator only applies to the first matched item in the query. For example:

> T. Find ();
{"_ Id": objectid ("4b9e4a1fc583fa1c76198319"), "x": [1, 2, 3, 2]}
> T. Update ({X: 2}, {$ Inc: {"x. $": 1 }}, false, true );
> T. Find ();
{"_ Id": objectid ("4b9e4a1fc583fa1c76198319"), "x": [1, 3, 3, 2]}

The Positional operator cannot be combined with an upsert since it requires a matching array element. If your update results in an insert then the "$" will literally be used as the field name.

Using "$ unset" with an expression like this "array. $ "will result in the array item becoming null, not being removed. you can issue an update with "{$ pull: {X: NULL}" to remove all nulls.

> T. insert ({X: [1, 3, 4, 3, 2, 3, 4]})
> T. Find ()
{"_ Id": objectid ("4bde2ad3755d00000000710e"), "x": [1, 2, 3, 4, 3, 2, 3, 4]}
> T. Update ({X: 3 },{$ unset: {"x. $": 1 }})
> T. Find ()
{"_ Id": objectid ("4bde2ad3755d00000000710e"), "x": [1, 2, null, 4, 3, 2, 3, 4]}

$ Pull can now do much of this so this example is now mostly historical (depending on your version ).
Upserts with Modifiers

You may use upsert with a modifier operation. in such a case, the modifiers will be applied to the update criteria Member and the resulting object will be inserted. the following upsert example may insert the object {name: "Joe", X: 1, Y: 1 }.

DB. People. Update ({name: "Joe" },{$ Inc: {X: 1, Y: 1 }}, true );

There are some restrictions. A modifier may not reference the _ id field, and two modifiers within an update may not reference the same field, for example the following is not allowed:

DB. People. Update ({name: "Joe"}, {$ Inc: {X: 1}, $ set: {X: 5 }});

Pushing a unique value

To add a value to an array only if not already present:

Starting in 1.3.3, you can do

Update ({_ ID: 'job'}, {"$ addtoset": {tags: "Baseball "}});

For older versions, add $ ne: <value> to your query expression:

Update ({_ ID: 'job', tags: {"$ ne": "Baseball "}},
{"$ Push": {tags: "Baseball "}});

Checking the outcome of an update request

As described above, a non-upsert update may or may not modify an existing object. an upsert will either modify an existing object or insert a new object. the client may determine if its most recent message on a connection updated an existing object by subsequently
Issuing a getlasterror command (dB. runcommand ("getlasterror ")). if the result of thegetlasterror command contains an updatedexisting field, the last message on the connection was an update request. if the updatedexisting field's value is true, that update
Request caused an existing object to be updated; If updatedexistingis false, no existing object was updated. an upserted field will contain the new _ id value if an insert is already med (New as of 1.5.4 ).
Notes
Object padding

When you update an object in MongoDB, the update occurs in-place if the object has not grown in size. This is good for insert performance if the collection has indexes.

Mongo adaptively learns if objects in a collection tend to grow, and if they do, it adds some padding to prevent excessive movements. This statistic is tracked separately for each collection.
Blocking

Staring in 1.5.2, multi updates yield occasionally so you can safely update large amounts of data. if you want a multi update to be truly isolated (so no other writes happen while processing the affected threads), you can use the $ atomic flag in the query
Like this:

DB. Students. Update ({score: {$ GT: 60}, $ atomic: true}, {$ set: {pass: true }})

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.