| coll.find(Filters.eq("title", "Hamlet")).first(); |
|
| coll.find(Filters.eq("year", 2005)) |
|
| coll.insertOne(new Document("title", "Jackie Robinson")); |
|
Insert Multiple Documents
| coll.insertMany( | Arrays.asList( | new Document("title", "Dangal").append("rating", "Not Rated"), | new Document("title", "The Boss Baby").append("rating", "PG"))); |
|
| coll.updateOne( | Filters.eq("title", "Amadeus"), | Updates.set("imdb.rating", 9.5)); |
|
Update Multiple Documents
| coll.updateMany( | Filters.eq("year", 2001), | Updates.inc("imdb.votes", 100)); |
|
Update an Array in a Document
| coll.updateOne( | Filters.eq("title", "Cosmos"), | Updates.push("genres", "Educational")); |
|
| coll.replaceOne( | Filters.and(Filters.eq("name", "Deli Llama"), Filters.eq("address", "2 Nassau St")), | new Document("name", "Lord of the Wings").append("zipcode", 10001)); |
|
| coll.deleteOne(Filters.eq("title", "Congo")); |
|
Delete Multiple Documents
| coll.deleteMany(Filters.regex("title", "^Shark.*")); |
|
| coll.bulkWrite( | Arrays.asList( | new InsertOneModel<Document>( | new Document().append("title", "A New Movie").append("year", 2022)), | new DeleteManyModel<Document>( | Filters.lt("year", 1970)))); |
|
| coll.watch(Arrays.asList( | Aggregates.match(Filters.gte("year", 2022)))); |
|
Access Data from a Cursor Iteratively
| MongoCursor<Document> cursor = coll.find().cursor(); | while (cursor.hasNext()) { | System.out.println(cursor.next().toJson()); | } |
|
Access Results from a Query as an Array
| List<Document> resultList = new ArrayList<Document>(); | coll.find().into(resultList); |
|
| coll.countDocuments(Filters.eq("year", 2000)); |
|
List the Distinct Documents or Field Values | coll.distinct("year", Integer.class); |
|
Limit the Number of Documents Retrieved
| |
| coll.find(Filters.regex("title", "^Rocky")).skip(2); |
|
Sort the Documents When Retrieving Them
| coll.find().sort(Sorts.ascending("year")); |
|
Project Document Fields When Retrieving Them
| coll.find().projection(Projections.fields( | Projections.excludeId(), | Projections.include("year", "imdb"))); |
|
| coll.createIndex( | Indexes.compoundIndex( | Indexes.ascending("title"), | Indexes.descending("year"))); |
|
| | coll.find(Filters.text("zissou")); |
|
Install the Driver Dependency with Maven | <dependencies> | <dependency> | <groupId>org.mongodb</groupId> | <artifactId>mongodb-driver-sync</artifactId> | <version>4.3.4</version> | </dependency> | </dependencies> |
|
Install the Driver Dependency with Gradle | dependencies { | implementation 'org.mongodb:mongodb-driver-sync:4.3.4' | } |
|