CRUD Java Flashcards
True or False
BSON objects are more secure than JSON objects
True. BSON objects are not vulnerable to JSON injection attacks
Which class does MongoDB recommend to represent BSON documents?
The Document
class
What is another name for “subdocument”?
Embedded document
Nested document
Code an example of inserting a single document
collection.insertOne(new Document(field, value));
Code an example of inserting multiple documents
var doc1 = new Document().append(field, value); var doc2 = new Document().append(field, value); List<Document> docs = Arrays.asList(doc1, doc2); // List.of(...) also works collection.insertMany(docs);
Which factory class should you use for query documents?
The Filters
class
Code an example of finding one document in the database
collection.find(eq(field, value)).first();
Code an example of obtaining and iterating through a cursor
try (var cursor = collection.find(eq(field, value)).cursor()) { while (cursor.hasNext()) { //... } }
True or False
An application should ensure that a cursor is closed in all circumstances, e.g. using a try-with-resources statement
True
Which factory class should you use for update operators?
The Updates
class
Code an example of updating multiple fields in a single document
collection.updateOne(query, combine(set(field, value), set(field2, value2)));
Code an example of inserting 2 documents to 2 different collections as a transaction
MongoClient client = MongoClients.create("..."); MongoCollection<Document> collection1 = client.getDatabase(name1).getCollection(name1); MongoCollection<Document> collection2 = client.getDatabase(name2).getCollection(name2); TransactionBody transaction = new TransactinBody<Void>() { public void execute() { collection1.insertOne(clientSession, new Document(field, value)); collection2.insertOne(clientSession, new Document(field, value)); } try (ClientSession clientSession = client.startSession()) { clientSession.withTransaction(transaction); }
True or False
Transactions can only be used for write operations
False. Transactions can be used for both read and write operations
True or False
Transactions are ACID compliant
True
True or False
By default, MongoDB will cancel any transaction that runs for more than 80 seconds
False. Its 60 seconds