本文整理匯總了Java中com.mongodb.client.MongoDatabase類的典型用法代碼示例。如果您正苦於以下問題:Java MongoDatabase類的具體用法?Java MongoDatabase怎麽用?Java MongoDatabase使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
MongoDatabase類屬於com.mongodb.client包,在下文中一共展示了MongoDatabase類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: getAllDocuments
import com.mongodb.client.MongoDatabase; //導入依賴的package包/類
/**
* This method retrieve all the document(s)
*/
@Override
public void getAllDocuments() {
MongoDatabase db = null;
MongoCollection collection = null;
try {
db = client.getDatabase(mongo.getDataBase());
collection = db.getCollection(mongo.getSampleCollection());
FindIterable<Document> docs = collection.find(); //SELECT * FROM sample;
for (Document doc : docs) {
log.info(doc.getString("name"));
}
} catch (MongoException | ClassCastException e) {
log.error("Exception occurred while insert Value using **BasicDBObject** : " + e, e);
}
}
示例2: deleteManyDocument
import com.mongodb.client.MongoDatabase; //導入依賴的package包/類
/**
* This is deleted delete all document(s), which is matched
*/
@Override
public void deleteManyDocument() {
MongoDatabase db = null;
MongoCollection collection = null;
Bson query = null;
try {
db = client.getDatabase(mongo.getDataBase());
collection = db.getCollection(mongo.getSampleCollection());
query = lt("age", 20);
DeleteResult result = collection.deleteMany(query);
if (result.wasAcknowledged()) {
log.info("Document deleted successfully \nNo of Document(s) Deleted : "
+ result.getDeletedCount());
}
} catch (MongoException e) {
log.error("Exception occurred while delete Many Document : " + e, e);
}
}
示例3: updateDocumentWithCurrentDate
import com.mongodb.client.MongoDatabase; //導入依賴的package包/類
/**
* This method update document with lastmodified properties
*/
@Override
public void updateDocumentWithCurrentDate() {
MongoDatabase db = null;
MongoCollection collection = null;
Bson filter = null;
Bson query = null;
try {
db = client.getDatabase(mongo.getDataBase());
collection = db.getCollection(mongo.getSampleCollection());
filter = eq("name", "Sundar");
query = combine(set("age", 23), set("gender", "Male"),
currentDate("lastModified"));
UpdateResult result = collection.updateOne(filter, query);
log.info("Update with date Status : " + result.wasAcknowledged());
log.info("No of Record Modified : " + result.getModifiedCount());
} catch (MongoException e) {
log.error("Exception occurred while update Many Document with Date : " + e, e);
}
}
示例4: deleteOneDocument
import com.mongodb.client.MongoDatabase; //導入依賴的package包/類
/**
* This is delete the single document, which is first matched
*/
@Override
public void deleteOneDocument() {
MongoDatabase db = null;
MongoCollection collection = null;
Bson query = null;
try {
db = client.getDatabase(mongo.getDataBase());
collection = db.getCollection(mongo.getSampleCollection());
query = eq("name", "sundar");
DeleteResult result = collection.deleteMany(query);
if (result.wasAcknowledged()) {
log.info("Single Document deleted successfully \nNo of Document Deleted : " + result.getDeletedCount());
}
} catch (MongoException e) {
log.error("Exception occurred while delete Single Document : " + e, e);
}
}
示例5: testInsert
import com.mongodb.client.MongoDatabase; //導入依賴的package包/類
@Test
@Ignore
public void testInsert() {
MongoClient mongoClient = new MongoClient("localhost", 27017);
try {
MongoDatabase db = mongoClient.getDatabase("prova");
MongoCollection<Document> coll = db.getCollection("prova");
Map<String, Object> map = new HashMap<String, Object>();
map.put("signature", "void test()");
map.put("param", convert(new Object[0]));
map.put("returnValue", 1);
map.put("exception", convert(new IllegalAccessError("prova")));
Document doc = new Document(map);
coll.insertOne(doc);
LOG.info(doc);
} catch (Exception e) {
LOG.error(e);
} finally {
mongoClient.close();
}
}
示例6: incrementMetadata
import com.mongodb.client.MongoDatabase; //導入依賴的package包/類
@Test
public void incrementMetadata() {
//This method is called from inside of getPlantByPlantId();
boolean myPlant = plantController.
incrementMetadata("58d1c36efb0cac4e15afd278", "pageViews");
assertFalse(myPlant);
boolean myPlant2 = plantController.incrementMetadata("16001.0","pageViews");
assertTrue(myPlant2);
//This is necessary to test the data separately from getPlantByPlantId();
Document searchDocument = new Document();
searchDocument.append("id", "16001.0");
MongoClient mongoClient = new MongoClient();
MongoDatabase db = mongoClient.getDatabase(databaseName);
MongoCollection<Document> plantCollection = db.getCollection("plants");
String before = JSON.serialize(plantCollection.find(searchDocument));
plantController.incrementMetadata("16001.0","pageViews");
String after = JSON.serialize(plantCollection.find(searchDocument));
assertFalse(before.equals(after));
}
開發者ID:UMM-CSci-3601-S17,項目名稱:digital-display-garden-iteration-3-sixguysburgers-fries,代碼行數:23,代碼來源:UnorganizedTests.java
示例7: successfulInputOfComment
import com.mongodb.client.MongoDatabase; //導入依賴的package包/類
@Test
public void successfulInputOfComment() throws IOException {
String json = "{ plantId: \"58d1c36efb0cac4e15afd278\", comment : \"Here is our comment for this test\" }";
assertTrue(plantController.addComment(json, "second uploadId"));
MongoClient mongoClient = new MongoClient();
MongoDatabase db = mongoClient.getDatabase(databaseName);
MongoCollection<Document> plants = db.getCollection("plants");
Document filterDoc = new Document();
filterDoc.append("_id", new ObjectId("58d1c36efb0cac4e15afd278"));
filterDoc.append("uploadID", "second uploadId");
Iterator<Document> iter = plants.find(filterDoc).iterator();
Document plant = iter.next();
List<Document> plantComments = (List<Document>) ((Document) plant.get("metadata")).get("comments");
long comments = plantComments.size();
assertEquals(1, comments);
assertEquals("Here is our comment for this test", plantComments.get(0).getString("comment"));
assertNotNull(plantComments.get(0).getObjectId("_id"));
}
開發者ID:UMM-CSci-3601-S17,項目名稱:digital-display-garden-iteration-4-dorfner-v2,代碼行數:26,代碼來源:TestPlantComment.java
示例8: executeInsert
import com.mongodb.client.MongoDatabase; //導入依賴的package包/類
/**
* @param dbName 表名
* @param collectionName 集合名
* @param saveJson 待存入JSON
* @return 插入狀態或異常信息
*/
@SuppressWarnings("unchecked")
public JSONObject executeInsert(String dbName, String collectionName, JSONObject saveJson) {
JSONObject resp = new JSONObject();
try {
MongoDatabase db = mongoClient.getDatabase(dbName);
MongoCollection coll = db.getCollection(collectionName);
Document doc = Document.parse(saveJson.toString());
coll.insertOne(doc);
} catch (MongoTimeoutException e1) {
e1.printStackTrace();
resp.put("ReasonMessage", e1.getClass() + ":" + e1.getMessage());
return resp;
} catch (Exception e) {
e.printStackTrace();
resp.put("ReasonMessage", e.getClass() + ":" + e.getMessage());
}
return resp;
}
示例9: AddFlowerRatingReturnsTrueWithValidJsonInput
import com.mongodb.client.MongoDatabase; //導入依賴的package包/類
@Test
public void AddFlowerRatingReturnsTrueWithValidJsonInput() throws IOException{
String json = "{like: true, id: \"58d1c36efb0cac4e15afd202\"}";
assertTrue(plantController.addFlowerRating(json, "first uploadId") instanceof ObjectId);
MongoClient mongoClient = new MongoClient();
MongoDatabase db = mongoClient.getDatabase(databaseName);
MongoCollection plants = db.getCollection("plants");
FindIterable doc = plants.find(new Document().append("_id", new ObjectId("58d1c36efb0cac4e15afd202")));
Iterator iterator = doc.iterator();
Document result = (Document) iterator.next();
List<Document> ratings = (List<Document>) ((Document) result.get("metadata")).get("ratings");
assertEquals(1, ratings.size());
Document rating = ratings.get(0);
assertTrue(rating.getBoolean("like"));
assertTrue(rating.get("id") instanceof ObjectId);
}
開發者ID:UMM-CSci-3601-S17,項目名稱:digital-display-garden-iteration-4-dorfner-v2,代碼行數:23,代碼來源:FlowerRating.java
示例10: BingoChessChallenge
import com.mongodb.client.MongoDatabase; //導入依賴的package包/類
public BingoChessChallenge(String[] args) {
announcer = new Chatter(args[0]);
lichs = new HashMap<String,Lichesser>();
chessplayers = new HashMap<String,ChessPlayer>();
chessgames = new HashMap<String,LichessGame>();
BingoPlayer.SQUARE_BAG = new Vector<Dimension>();
for (int x=0;x<8;x++)
for (int y=0;y<8;y++)
BingoPlayer.SQUARE_BAG.add(new Dimension(x,y));
initIRC(args[0], args[1], args[2], args[3]);
loadAdmins("res/admins.txt");
serv = new BingoServ(Integer.parseInt(args[4]),this);
serv.startSrv();
bingoURL = args[5];
MongoClientURI connStr = new MongoClientURI("mongodb://bingobot:" + args[6] + "@localhost:27017/BingoBase");
MongoClient mongoClient = new MongoClient(connStr);
MongoDatabase bingoBase = mongoClient.getDatabase("BingoBase");
playData = bingoBase.getCollection("players");
}
示例11: insertSingleDocument
import com.mongodb.client.MongoDatabase; //導入依賴的package包/類
/**
* This method insert the single document
*/
@Override
public void insertSingleDocument() {
MongoDatabase db = null;
MongoCollection collection = null;
try {
db = client.getDatabase(mongo.getDataBase());
collection = db.getCollection(mongo.getSampleCollection());
Document canvas = new Document("item", "canvas").append("qty", 100)
.append("tags", singletonList("cotton"));
Document size = new Document("h", 28).append("w", 35.5).append(
"uom", "cm");
canvas.append("size", size);
collection.insertOne(canvas);
log.info("Single Document Insert Successfully...");
} catch (MongoException | ClassCastException e) {
log.error("Exception occurred while insert **Single Document** : " + e, e);
}
}
示例12: initCollections
import com.mongodb.client.MongoDatabase; //導入依賴的package包/類
private static void initCollections(MongoDatabase db) {
try {
db.createCollection("users");
db.createCollection("categories");
db.createCollection("feeds");
db.createCollection("licenses");
} catch (Exception e) {
Log.w(TAG, "[attemptCreateCollections] " + e.getMessage());
}
users = db.getCollection("users");
categories = db.getCollection("categories");
feeds = db.getCollection("feeds");
licenses = db.getCollection("licenses");
users.createIndex(
Indexes.ascending(User.USERNAME),
new IndexOptions().unique(true));
categories.createIndex(
Indexes.ascending(Category.OWNER, Category.KEY),
new IndexOptions().unique(true));
}
示例13: find
import com.mongodb.client.MongoDatabase; //導入依賴的package包/類
@Override
public List<Document> find(String collection, String signature) {
List<Document> res = new ArrayList<Document>();
try {
MongoDatabase db = mongoClient.getDatabase(databaseName);
MongoCollection<Document> coll = db.getCollection(collection);
BasicDBObject searchQuery = new BasicDBObject();
searchQuery.put("signature", signature);
Iterable<Document> docs = coll.find(searchQuery);
for (Document doc : docs) {
res.add(doc);
}
} catch (Exception e) {
LOG.error(e);
}
return res;
}
示例14: saveEntry
import com.mongodb.client.MongoDatabase; //導入依賴的package包/類
/**
* Saves an entry to file
* @param entry
* @param dbName usually scrapig
* @return true if success
*/
public static boolean saveEntry(DBEntry entry, String dbName){
if(entry == null || !entry.isValid())
return false;
Logger log = Logger.getLogger(DAO.class);
MongoDatabase db = MongoDB.INSTANCE.getDatabase(dbName);
String collectionName = getCollectionName(entry);
MongoCollection collection = db.getCollection(collectionName,BasicDBObject.class);
try {
collection.insertOne(entry);
return true;
}
catch (MongoWriteException ex){
if (ex.getCode() != 11000) // Ignore errors about duplicates
log.error(ex.getError().getMessage());
return false;
}
}
示例15: populateDatabase
import com.mongodb.client.MongoDatabase; //導入依賴的package包/類
public static void populateDatabase(String[][] cellValues){
MongoClient mongoClient = new MongoClient();
MongoDatabase ddg = mongoClient.getDatabase("ddg");
MongoCollection plants = ddg.getCollection("flowers");
plants.drop();
String[] keys = getKeys(cellValues);
for (int i = 4; i < cellValues.length; i++){
Map<String, String> map = new HashMap<String, String>();
for(int j = 0; j < cellValues[i].length; j++){
map.put(keys[j], cellValues[i][j]);
}
Document doc = new Document();
doc.putAll(map);
doc.append("thumbsUp", 0);
doc.append("flowerVisits", 0);
plants.insertOne(doc);
}
}
開發者ID:UMM-CSci-3601-S17,項目名稱:digital-display-garden-iteration-2-spraguesanborn,代碼行數:22,代碼來源:ExcelParser.java