Getting Started with MongoDB and Java: Part II
This blog post from năm trước is now very deprecated. Many things changed in the Java driver since then. Please kiểm tra out the mới ra Java tutorials on the Developer Hub. Java – CRUD Operations Tutorial Java – Mapping POJOs Java – Aggxổ số shbet
ation Pipeline Java – Change Streams By Trisha Gee, Java Engineer and Advocate at MongoDB In the last article, we covered the basics of installing và connecting lớn MongoDB via a Java application. In this post, I’ll give an introduction béo CRUD ( Create, Read, Update, Delete ) operations using the Java driver. As in the previous article, if you want lớn follow along và code as we go, you can use these tips lớn get the tests in the Getting Started project Khủng go green. Creating documents In the last article, we introduced documents và how mập create them from Java và insert them into MongoDB, so sánh I’m not going Khủng repeat that here. But if you want a reminder, or simply want Khủng skip béo playing with the code, you can take a look at Exercise3InsertTest. Querying Putting stuff in the database is all well và good, but you’ll probably want bự query the database mập get dữ liệu from it. In the last article we covered some basics on using find ( ) mập get dữ liệu from the database. We also showed an example in Exercise4RetrieveTest. But MongoDB supports more than simply getting a single document by ID or getting all the documents in a collection. As I mentioned, you can query by example, building up a query document that looks a similar shape béo the one you want. For the following examples I’m going phệ assume a document which looks something lượt thích this : person = { _id : ” anId “, name : ” A Name “, address : { street : ” Street Address “, đô thị : ” City “, phone : ” 12345 ” } books : [ 27464, 747854, … ] } Find a document by ID To recap, you can easily get a document back from the database using the quality ID : DBCursor cursor = collection.find ( new BasicDBObject ( ” _id “, ” theId ” ) ) ; … & you get the values out of the document ( represented as a DBObject ) using a Map – lượt thích syntax : ( String ) cursor.one ( ). get ( ” name ” ) In the above example, because you’ve queried by ID ( & you knew that ID existed ), you can be sure that the cursor has a single document that matches the query. Therefore you can use cursor.one ( ) Khủng get it. Find all documents matching some criteria In the real world, you won’t always know the ID of the document you want. You could be looking for all the people with a particular name, for example. In this case, you can create a query document that has the criteria you want : DBCursor results = collection.find ( new BasicDBObject ( ” name “, ” The name I want mập find ” ) ) ; You can find out the number of results : results.size ( ) ; và you can, naturally, iterate kết thúc them : for ( DBObject result : results ) { / / vì something with each result } A note on batching The cursor will fetch results in batches from the database, so sánh if you run a query that matches a lot of documents, you don’t have mập worry that every document is loaded into memory immediately. For most queries, the first batch returned will be 101 documents. But as you iterate kết thúc the cursor, the driver will automatically fetch further batches from the hệ thống. So you don’t have mập worry about managing batching in your application. But you vì need bự be aware that if you iterate kết thúc the whole of the cursor ( for example bự put it into a List ), you will kết thúc up fetching all the results & putting them in memory. You can get started with Exercise5SimpleQueryTest. Selecting Fields Generally speaking, you will read entire documents from MongoDB most of the phút giây. However, you can choose béo return just the fields that you care about ( for example, you might have a large document & not need all the values ). You vì this by passing a second parameter into the find method that’s another DBObject defining the fields you want Khủng return. In this example, we’ll tìm kiếm for people called “ Smith ”, và return only the name field. To bởi vì this we pass in a DBObject representing { name : một } : DBCursor results = collection.find ( new BasicDBObject ( ” name “, ” SomeName ” ), hot nhất BasicDBObject ( ” name “, một ) ) ; You can also use this method béo exclude fields from the results. Maybe we might want lớn exclude an unnecessary subdocument from the results – let’s say we want mập find everyone called “ Smith ”, but we don’t want lớn return the address. We bởi this by passing in a zero for this field name, i. e. { address : 0 } : DBCursor results = collection.find ( new BasicDBObject ( ” name “, ” SomeName ” ), mới ra BasicDBObject ( ” address “, 0 ) ) ; With this information, you’re ready bự tackle Exercise6SelectFieldsTest Query Operators As I mentioned in the previous article, your fields can be one of a number of types, including numeric. This means that you can vì queries for numeric values as well. Let’s assume, for example, that our person has a numberOfOrders field, & we wanted phệ find everyone who had ordered more than, let’s say, 10 items. You can bởi this using the USD gt operator : DBCursor results = collection.find ( new BasicDBObject ( ” numberOfOrders “, mới nhất BasicDBObject ( ” USD gt “, 10 ) ) ) ; chú ý that you have lớn create a further subdocument containing the USD gt condition béo use this operator. All of the query operators are documented, và work in a similar way mập this example. You might be wondering what terrible things could happen if you try lớn perform some sort of numeric comparison on a field that is a String, since the database supports any type of value in any of the fields ( và in Java the values are Objects so sánh you don’t get the benefit of type safety ). So, what happens if you bởi this ? DBCursor results = collection.find ( new BasicDBObject ( ” name “, mới ra BasicDBObject ( ” USD gt “, 10 ) ) ) ; The answer is you get zero results ( assuming all your documents contain names that are Strings ), & you don’t get any errors. The flexible nature of the document schema allows you béo phối & match types và query without error. You can use this technique phệ get the kiểm tra in Exercise7QueryOperatorsTest lớn go green – it’s a bit of a daft example, but you get the idea. Querying Subdocuments So far we’ve assumed that we only want mập query values in our top-level fields. However, we might want lớn query for values in a subdocument – for example, with our person document, we might want bự find everyone who lives in the same thành phố. We can use dot notation lượt thích this : DBObject findLondoners = mới nhất BasicDBObject ( ” address.city “, ” London ” ) ; collection.find ( findLondoners ) ) ; We’re not going Khủng use this technique in a query thử nghiệm, but we will use it later when we’re doing updates. Familiar methods I mentioned earlier that you can iterate kết thúc a cursor, và that the driver will fetch results in batches. However, you can also use the familiar-looking skip ( ) & limit ( ) methods. You can use these phệ fix up the demo in Exercise8SkipAndLimitTest. A last note on querying : Indexes Like a traditional database, you can add indexes onto the database phệ improve the tốc độ of regular queries. There’s extensive documentation on indexes which you can read at your own leisure. However, it is worth pointing out that, if necessary, you can programmatically create indexes via the Java driver, using createIndexes. For example : collection. createIndex ( new BasicDBObject ( ” fieldToIndex “, một ) ) ; There is a very simple example for creating an index in Exercise9IndexTest, but indexes are a đầy đủ topic on their own, và the purpose of this part of the tutorial is béo merely make you aware of their existence rather than provide a comprehensive tutorial on their purpose & uses. Updating values Now you can insert into & read from the database. But your dữ liệu is probably not static, especially as one of the benefits of MongoDB is a flexible schema that can evolve with your needs end phút giây. In order phệ cập nhật values in the database, you’ll have Khủng define the query criteria that states which document ( s ) you want béo cập nhật, và you’ll have lớn pass in the document that represents the updates you want Khủng make. There are a few things lớn be aware of when you’re updating documents in MongoDB, once you understand these it’s as simple as everything else we’ve seen so sánh far. Firstly, by mặc định only the first document that matches the query criteria is updated. Secondly, if you pass in a document as the value béo cập nhật béo, this hot nhất document will replace the whole existing document. If you think about it, the common use-case will be : you retrieve something from the database ; you modify it based on some criteria from your application or the user ; then you save the updated document béo the database. I’ll show the various types of updates ( và point you lớn the code in the chạy thử class ) béo walk you through these different cases. Simple Update : Find a document và replace it with an updated one We’ll carry on using our simple Person document for our examples. Let’s assume we’ve got a document in our database that looks lượt thích : person = { _id : ” jo “, name : ” Jo Bloggs “, address : { street : ” 123 Fake St “, thành phố : ” Faketon “, phone : ” 5559991234 ” } books : [ 27464, 747854, … ] } Maybe Jo goes into witness protection & needs Khủng change his / her name. Assuming we’ve got jo populated in a DBObject, we can make the appropriate changes lớn the document và save it into the database : DBObject jo = / / get the document representing jo jo.put ( ” name “, ” Jo In Disguise ” ) ; / / replace the old name with the hot nhất one collection.update ( new BasicDBObject ( ” _id “, ” jo ” ), / / find jo by ID jo ) ; / / phối the document in the DB bự the mới nhất document for Jo You can make a start with Exercise10UpdateByReplacementTest. Update Operators : Change a field But sometimes you won’t have the whole document bự replace the old one, sometimes you just want Khủng cập nhật a single field in whichever document matched your criteria. Let’s imagine that we only want lớn change Jo’s phone number, & we don’t have a DBObject with all of Jo’s details but we bởi vì have the ID of the document. If we use the USD mix operator, we’ll replace only the field we want mập change : collection.update ( new BasicDBObject ( ” _id “, ” jo ” ), mới nhất BasicDBObject ( ” USD phối “, hot nhất BasicDBObject ( ” phone “, ” 5559874321 ” ) ) ) ; There are a number of other operators for performing updates on documents, for example USD inch which will increment a numeric field by a given amount. Now you can vì Exercise11UpdateAFieldTest Update Multiple As I mentioned earlier, by mặc định the cập nhật operation updates the first document it finds và no more. You can, however, phối the multi flag on cập nhật béo cập nhật everything. So maybe we want Khủng cập nhật everyone in the database mập have a country field, và for now we’re going phệ assume all the current people are in the UK : collection.update ( new BasicDBObject ( ), hot nhất BasicDBObject ( ” USD phối “, mới nhất BasicDBObject ( ” country “, ” UK ” ) ), false, true ) ; The query parameter is an empty document which finds everything ; the second boolean ( mix béo true ) is the flag that says lớn cập nhật all the values which were found. Now we’ve learnt enough lớn complete the two tests in Exercise12UpdateMultipleDocumentsTest Upsert Finally, the last thing bự mention when updating documents is Upsert ( Update-or-Insert ). This will tìm kiếm for a document matching the criteria và either : cập nhật it if it’s there ; or insert it into the database if it wasn’t. Like “ cập nhật multiple ”, you define an upsert operation with a magic boolean. It shouldn’t come as a surprise béo find it’s the first boolean param in the cập nhật statement ( since “ multi ” was the second ) : collection.update ( query, personDocument, true, false ) ; Now you know everything you need phệ complete the chạy thử in Exercise13UpsertTest Removing from the database Finally the D in CRUD – Delete. The syntax of a remove should look familiar now we’ve got this far, you pass a document that represents your selection criteria into the remove method. So if we wanted bự delete jo from our database, we’d bởi vì : collection.remove ( new BasicDBObject ( ” _id “, ” jo ” ) ) ; Unlike update, if the query matches more than one document, all those documents will be deleted ( something mập be aware of ! ). If we wanted lớn remove everyone who lives in London, we’d need lớn bởi : collection.remove ( new BasicDBObject ( ” address.city “, ” London ” ) ) ; That’s all there is lớn remove, you’re ready Khủng finish off Exercise14RemoveTest Conclusion Unlike traditional databases, you don’t create SQL queries in MongoDB phệ perform CRUD operations. Instead, operations are done by constructing documents both phệ query the database, & Khủng define the operations bự perform. While we’ve covered what the basics look lượt thích in Java, there’s loads more documentation on all the core concepts in the MongoDB documentation : Query Documents CRUD Operations Indexes Get Started with MongoDB Atlas Run MongoDB in the cloud for không lấy phí with MongoDB Atlas. No credit thẻ required. Get Started
August 14, năm trước
Source: https://ontopwiki.com
Leave a Comment