下面列出了怎么用com.mongodb.client.MongoCollection的API类实例代码及写法,或者点击链接到github查看源代码。
private <T> List<T> list(MongoCollection<Document> collection, Class<T> clz) {
List<T> result = new LinkedList<T>();
collection.find().map(new Function<Document, T>() {
@Override
public T apply(Document t) {
String json = t.toJson();
try {
return mapper.readValue(json, clz);
} catch (IOException e) {
LOG.error("deserialize config item failed!", e);
}
return null;
}
}).into(result);
return result;
}
private static void loadRecords(int totalRecords, String dataset, MongoCollection mc) throws IOException {
List<Document> documents = new ArrayList<>(totalRecords);
try(InputStream inputStream = QueryConverterIT.class.getResourceAsStream("/" + dataset + ".json");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream))) {
String line;
while ((line = bufferedReader.readLine())!=null) {
documents.add(Document.parse(line));
}
}
for (Iterator<List<WriteModel>> iterator = Iterables.partition(Lists.transform(documents, new Function<Document, WriteModel>() {
@Override
public WriteModel apply(Document document) {
return new InsertOneModel(document);
}
}),10000).iterator(); iterator.hasNext();) {
mc.bulkWrite(iterator.next());
}
}
private static void persistOrUpdate(MongoCollection collection, List<Object> entities) {
//this will be an ordered bulk: it's less performant than a unordered one but will fail at the first failed write
List<WriteModel> bulk = new ArrayList<>();
for (Object entity : entities) {
//we transform the entity as a document first
BsonDocument document = getBsonDocument(collection, entity);
//then we get its id field and create a new Document with only this one that will be our replace query
BsonValue id = document.get(ID);
if (id == null) {
//insert with autogenerated ID
bulk.add(new InsertOneModel(entity));
} else {
//insert with user provided ID or update
BsonDocument query = new BsonDocument().append(ID, id);
bulk.add(new ReplaceOneModel(query, entity,
new ReplaceOptions().upsert(true)));
}
}
collection.bulkWrite(bulk);
}
public int getResourceType(String key) throws OneM2MException {
MongoCollection<Document> collection = context.getDatabaseManager()
.getCollection(collectionName);
Document doc = collection.find(new BasicDBObject(OneM2mUtil.isUri(key) ? URI_KEY : RESID_KEY, key)).first();
if (doc == null) {
throw new OneM2MException(RESPONSE_STATUS.NOT_FOUND,
"resource not found(" + key + ")");
}
int resType = (int) doc.get(Naming.RESOURCETYPE_SN);
if (resType == RESOURCE_TYPE.MGMT_OBJ.Value()){
return (int) doc.get(Naming.MGMTDEFINITION_SN);
}
// return (int)doc.get("resourceType");
return (int) doc.get(Naming.RESOURCETYPE_SN);
}
public void saveTagAssignment(final Coordinates coordinates, final SingleTagAssignment singleTagAssignment) {
final MongoCollection<TagAssignments> tagAssignments = getTagAssignmentColletions();
final CoordinatesDto coordinatesDto = CoordinatesMapper.mapCoordinates(coordinates);
final Bson query = Filters.eq("coordinates", coordinatesDto);
final TagAssignments savedAssignments = tagAssignments.find(query).first();
if (savedAssignments == null) {
final TagAssignments newAssignments = new TagAssignments();
newAssignments.setCoordinates(coordinatesDto);
newAssignments.setTags(Arrays.asList(singleTagAssignment));
tagAssignments.insertOne(newAssignments);
} else {
savedAssignments.getTags().removeIf(single -> single.getTag().equals(singleTagAssignment.getTag()));
savedAssignments.getTags().add(singleTagAssignment);
tagAssignments.replaceOne(query, savedAssignments);
}
}
private MongoCollection createMongoCollection(
Stage.Context context,
List<Stage.ConfigIssue> issues,
ReadPreference readPreference,
WriteConcern writeConcern
) {
MongoCollection mongoCollection = null;
try {
if (readPreference != null) {
mongoCollection = mongoDatabase.getCollection(collection).withReadPreference(readPreference);
} else if (writeConcern != null) {
mongoCollection = mongoDatabase.getCollection(collection).withWriteConcern(writeConcern);
}
} catch (MongoClientException e) {
issues.add(context.createConfigIssue(
Groups.MONGODB.name(),
MONGO_CONFIG_PREFIX + "collection",
Errors.MONGODB_03,
collection,
e.toString()
));
}
return mongoCollection;
}
public int getResourceType(String key) throws OneM2MException {
MongoCollection<Document> collection = context.getDatabaseManager()
.getCollection(collectionName);
Document doc = collection.find(new BasicDBObject(OneM2mUtil.isUri(key) ? URI_KEY : RESID_KEY, key)).first();
if (doc == null) {
throw new OneM2MException(RESPONSE_STATUS.NOT_FOUND,
"resource not found(" + key + ")");
}
int resType = (int) doc.get(Naming.RESOURCETYPE_SN);
if (resType == RESOURCE_TYPE.MGMT_OBJ.Value()){
return (int) doc.get(Naming.MGMTDEFINITION_SN);
}
// return (int)doc.get("resourceType");
return (int) doc.get(Naming.RESOURCETYPE_SN);
}
private static MongoCollection<Document> getOrCreateMongoCollection(final MongoDatabase database,
final String collectionName, final boolean isCapped, final Integer sizeInBytes) {
try {
LOGGER.debug("Gettting collection '{}'...", collectionName);
// throws IllegalArgumentException if collectionName is invalid
final MongoCollection<Document> found = database.getCollection(collectionName);
LOGGER.debug("Got collection {}", found);
return found;
} catch (final IllegalStateException e) {
LOGGER.debug("Collection '{}' does not exist.", collectionName);
final CreateCollectionOptions options = new CreateCollectionOptions().capped(isCapped)
.sizeInBytes(sizeInBytes);
LOGGER.debug("Creating collection '{}' with options {}...", collectionName, options);
database.createCollection(collectionName, options);
LOGGER.debug("Created collection.");
final MongoCollection<Document> created = database.getCollection(collectionName);
LOGGER.debug("Got created collection {}", created);
return created;
}
}
@Override
protected Supplier<Stream<DependencyTreeMatcher>> createPatternsSupplier()
throws DependencyParseException {
return new Supplier<Stream<DependencyTreeMatcher>>() {
MongoDatabase db = mongoResource.getDB();
final MongoCollection<Document> coll = db.getCollection(patternsCollection);
@Override
public Stream<DependencyTreeMatcher> get() {
return StreamSupport.stream(coll.find().spliterator(), false)
.map(
document -> {
try {
return DependencyTreeMatcher.create(document.getString(patternField));
} catch (DependencyParseException e) {
return null;
}
})
.filter(Predicates.notNull());
}
};
}
private void updateInitialRecordTime(String subscriptionID, String initialRecordTime) {
MongoCollection<BsonDocument> collection = Configuration.mongoDatabase.getCollection("Subscription",
BsonDocument.class);
BsonDocument subscription = collection.find(new BsonDocument("subscriptionID", new BsonString(subscriptionID)))
.first();
subscription.put("initialRecordTime", new BsonString(initialRecordTime));
if (subscription != null) {
collection.findOneAndReplace(new BsonDocument("subscriptionID", new BsonString(subscriptionID)),
subscription);
}
Configuration.logger.log(Level.INFO,
"InitialRecordTime of Subscription ID: " + subscriptionID + " is updated to DB. ");
}
public void updateStatsForFeatures(final Coordinates coordinates, final List<XbddFeature> features) {
final MongoCollection<Stats> statsCollection = getStatsCollection();
// product and version are redundant for search, but ensure they're populated if the upsert results in an insert.
final String id = coordinates.getProduct() + "/" + coordinates.getVersionString() + "/" + coordinates.getBuild();
statsCollection.deleteOne(Filters.eq(id));
final Stats newStats = new Stats();
newStats.setCoordinates(CoordinatesMapper.mapCoordinates(coordinates));
newStats.setId(id);
newStats.setSummary(getNewStatsSummary());
for (final XbddFeature xbddFeature : features) {
if (xbddFeature.getElements() != null) {
for (final XbddScenario scenario : xbddFeature.getElements()) {
final List<String> stepStatuses = FeatureMapper.getStepStatusStream(scenario).collect(Collectors.toList());
final String status = StatusHelper.reduceStatuses(stepStatuses).getTextName();
newStats.getSummary().replace(status, newStats.getSummary().get(status) + 1);
}
}
}
statsCollection.insertOne(newStats);
}
/**
* Executes a "find" operation on the underlying collection.
*
* <p>For example,
* <code>zipsTable.find("{state: 'OR'}", "{city: 1, zipcode: 1}")</code></p>
*
* @param mongoDb MongoDB connection
* @param filterJson Filter JSON string, or null
* @param projectJson Project JSON string, or null
* @param fields List of fields to project; or null to return map
* @return Enumerator of results
*/
private Enumerable<Object> find(MongoDatabase mongoDb, String filterJson,
String projectJson, List<Map.Entry<String, Class>> fields) {
final MongoCollection collection =
mongoDb.getCollection(collectionName);
final Bson filter =
filterJson == null ? null : BsonDocument.parse(filterJson);
final Bson project =
projectJson == null ? null : BsonDocument.parse(projectJson);
final Function1<Document, Object> getter = MongoEnumerator.getter(fields);
return new AbstractEnumerable<Object>() {
public Enumerator<Object> enumerator() {
@SuppressWarnings("unchecked") final FindIterable<Document> cursor =
collection.find(filter).projection(project);
return new MongoEnumerator(cursor.iterator(), getter);
}
};
}
private SetMultimap<ReNounFact, ScoredPattern> getFactToScoredPatternMultimap(
MongoCollection<Document> factsCollection,
MongoCollection<Document> scoredPatternsCollection) {
SetMultimap<ReNounFact, ScoredPattern> factToPatternMap = HashMultimap.create();
MongoCursor<Document> scoredPatternsCursor = scoredPatternsCollection.find().iterator();
while (scoredPatternsCursor.hasNext()) {
Document scoredPatternDocument = scoredPatternsCursor.next();
Iterator<Document> factsMatchingScoredPatternIterator =
factsCollection
.find(eq(PATTERN_FACT_FIELD, scoredPatternDocument.get(PATTERN_FACT_FIELD)))
.iterator();
while (factsMatchingScoredPatternIterator.hasNext()) {
Document factMatchingScoredPattern = factsMatchingScoredPatternIterator.next();
ReNounFact fact = new ReNounFact(factMatchingScoredPattern);
ScoredPattern scoredPattern = new ScoredPattern(scoredPatternDocument);
factToPatternMap.put(fact, scoredPattern);
}
}
return factToPatternMap;
}
public HashMap<String, Object> getAttributes(String keyName,
String keyValue, List<String> attrNames) throws OneM2MException {
MongoCollection<Document> collection = context.getDatabaseManager()
.getCollection(collectionName);
Document doc = collection.find(new BasicDBObject(keyName, keyValue))
.first();
if (doc == null) {
throw new OneM2MException(RESPONSE_STATUS.NOT_FOUND,
"resource not found");
}
HashMap<String, Object> results = new HashMap<String, Object>();
Iterator<String> it = attrNames.iterator();
while (it.hasNext()) {
String attr = it.next();
results.put(attr, doc.get(attr));
}
return results;
}
public HashMap<String, Object> getAttributes(String keyName,
String keyValue, List<String> attrNames) throws OneM2MException {
MongoCollection<Document> collection = context.getDatabaseManager()
.getCollection(collectionName);
Document doc = collection.find(new BasicDBObject(keyName, keyValue))
.first();
if (doc == null) {
throw new OneM2MException(RESPONSE_STATUS.NOT_FOUND,
"resource not found");
}
HashMap<String, Object> results = new HashMap<String, Object>();
Iterator<String> it = attrNames.iterator();
while (it.hasNext()) {
String attr = it.next();
results.put(attr, doc.get(attr));
}
return results;
}
private boolean takeOverTransactionInMongoDB(TransactionXid transactionXid, String source, String target) {
byte[] global = transactionXid.getGlobalTransactionId();
String instanceId = ByteUtils.byteArrayToString(global);
try {
String application = CommonUtils.getApplication(this.endpoint);
String databaseName = application.replaceAll("\\W", "_");
MongoDatabase mdb = this.mongoClient.getDatabase(databaseName);
MongoCollection<Document> collection = mdb.getCollection(CONSTANTS_TB_LOCKS);
Bson globalFilter = Filters.eq(CONSTANTS_FD_GLOBAL, instanceId);
Bson instIdFilter = Filters.eq("identifier", source);
Document document = new Document("$set", new Document("identifier", target));
UpdateResult result = collection.updateOne(Filters.and(globalFilter, instIdFilter), document);
return result.getMatchedCount() == 1;
} catch (RuntimeException rex) {
logger.error("Error occurred while locking transaction(gxid= {}).", instanceId, rex);
return false;
}
}
private MongoBlock fetchBlock(Integer blockNumber, boolean createIfNotExist) throws IOException {
MongoCollection<Document> c = mongoDirectory.getBlocksCollection();
Document query = new Document();
query.put(MongoDirectory.FILE_NUMBER, fileNumber);
query.put(MongoDirectory.BLOCK_NUMBER, blockNumber);
Document result = c.find(query).first();
byte[] bytes;
if (result != null) {
bytes = ((Binary) result.get(MongoDirectory.BYTES)).getData();
return new MongoBlock(this, blockNumber, bytes);
}
if (createIfNotExist) {
bytes = new byte[blockSize];
MongoBlock mongoBlock = new MongoBlock(this, blockNumber, bytes);
storeBlock(mongoBlock);
return mongoBlock;
}
return null;
}
public List<Document> getDocuments(String keyName, String keyValue,
RESOURCE_TYPE resType, String sortKey, boolean asc, int limit) {
ArrayList<Document> docList = new ArrayList<Document>();
BasicDBObject query = new BasicDBObject(keyName, keyValue).append(
RESTYPE_KEY, resType.Value());
BasicDBObject sort = new BasicDBObject(sortKey, asc ? 1 : -1);
MongoCollection<Document> collection = context.getDatabaseManager()
.getCollection(collectionName);
MongoCursor<Document> cursor = collection.find(query).sort(sort)
.limit(limit).iterator();
while (cursor.hasNext()) {
docList.add(cursor.next());
}
return docList;
}
@Override
public <N extends Node> List<NodeEntry<UUID, N>> searchUserNodes(ConstraintNodeMatcher<N> constraint) throws Exception {
List<NodeEntry<UUID, N>> held = new ArrayList<>();
MongoCollection<Document> c = this.database.getCollection(this.prefix + "users");
try (MongoCursor<Document> cursor = c.find().iterator()) {
while (cursor.hasNext()) {
Document d = cursor.next();
UUID holder = getDocumentId(d);
Set<Node> nodes = new HashSet<>(nodesFromDoc(d));
for (Node e : nodes) {
N match = constraint.match(e);
if (match != null) {
held.add(NodeEntry.of(holder, match));
}
}
}
}
return held;
}
/**
* 根据oid去数据库回查数据
*
* @param oid
* @return
*/
private Document fetchData(String schemaName, String tableName, String oid) {
Document result = null;
DbusDatasource datasource = GlobalCache.getDatasource();
MongoClientURI uri = new MongoClientURI(datasource.getMasterUrl());
MongoClient client = new MongoClient(uri);
MongoDatabase database = client.getDatabase(schemaName);
MongoCollection<Document> collection = database.getCollection(tableName);
MongoCursor<Document> cursor = collection.find(new BasicDBObject().append("_id", new ObjectId(oid))).iterator();
if (cursor.hasNext()) {
result = cursor.next();
} else {
logger.error("get source data error. schemaName:{}, tableName:{}, oid:{}", schemaName, tableName, oid);
}
client.close();
return result;
}
@Override
public JSONArray find(String key, String collection, JSONObject where, int limit, int skip) {
MongoCollection<Document> mc = getCollection(key, collection);
if (mc == null)
return new JSONArray();
FindIterable<Document> fi = mc.find(toDocument(where));
if (limit > 0)
fi.limit(limit);
if (skip > 0)
fi.skip(skip);
JSONArray array = new JSONArray();
for (Document document : fi)
array.add(JSON.parseObject(document.toJson()));
return array;
}
/**
* @return
*/
public List<Park> getAll() {
System.out.println("[DEBUG] MongoDBConnection.getAll()");
ArrayList<Park> allParksList = new ArrayList<Park>();
if (mongoDB != null) {
try {
MongoCollection parks = mongoDB.getCollection(COLLECTION);
MongoCursor<Document> cursor = parks.find().iterator();
try {
while (cursor.hasNext()) {
allParksList.add(ParkReadConverter.convert(cursor.next()));
}
} finally {
cursor.close();
}
} catch (Exception e) {
System.out.println("[ERROR] Error connecting to MongoDB. " + e.getMessage());
}
} else {
System.out.println("[ERROR] mongoDB could not be initiallized. No operation with DB will be performed");
}
return allParksList;
}
public void updateZForTiles(final StackId stackId,
final Double z,
final List<String> tileIds)
throws IllegalArgumentException, IllegalStateException {
MongoUtil.validateRequiredParameter("stackId", stackId);
MongoUtil.validateRequiredParameter("z", z);
MongoUtil.validateRequiredParameter("tileIds", tileIds);
final MongoCollection<Document> tileCollection = getTileCollection(stackId);
final Document query = new Document("tileId", new Document("$in", tileIds));
final Document update = new Document("$set", new Document("z", z));
final UpdateResult result = tileCollection.updateMany(query, update);
final String shortQueryForLog = "{ 'tileId': { '$in': [ " + tileIds.size() + " tile ids ... ] } }";
LOG.debug("updateZForTiles: updated {} tile specs with {}.update({},{})",
result.getModifiedCount(), MongoUtil.fullName(tileCollection), shortQueryForLog, update.toJson());
}
@Override
public Optional<Group> loadGroup(String name) {
Group group = this.plugin.getGroupManager().getIfLoaded(name);
if (group != null) {
group.getIoLock().lock();
}
try {
MongoCollection<Document> c = this.database.getCollection(this.prefix + "groups");
try (MongoCursor<Document> cursor = c.find(new Document("_id", name)).iterator()) {
if (!cursor.hasNext()) {
return Optional.empty();
}
if (group == null) {
group = this.plugin.getGroupManager().getOrMake(name);
group.getIoLock().lock();
}
Document d = cursor.next();
group.setNodes(DataType.NORMAL, nodesFromDoc(d));
}
} finally {
if (group != null) {
group.getIoLock().unlock();
}
}
return Optional.of(group);
}
public RyaStatementBindingSetCursorIterator(final MongoCollection<Document> coll,
final Multimap<RyaStatement, BindingSet> rangeMap, final MongoDBStorageStrategy<RyaStatement> strategy,
final Authorizations auths) {
this.coll = coll;
this.rangeMap = rangeMap;
queryIterator = rangeMap.keySet().iterator();
this.strategy = strategy;
this.auths = auths;
}
public void func1(final MongoCollection collection, final Object starts, final boolean setParallel,
final boolean setPathEnabled, final Class elementClass) {
currentPath = new HashMap<Object, Object>();
if (starts instanceof ChronoGraph || starts instanceof ChronoVertex || starts instanceof ChronoEdge
|| starts instanceof VertexEvent || starts instanceof EdgeEvent || starts instanceof EPCTime) {
HashSet set = new HashSet();
set.add(starts);
if (setParallel == true)
stream = set.parallelStream();
else
stream = set.stream();
this.elementClass = starts.getClass();
if (setPathEnabled) {
HashSet initPathSet = new HashSet();
List list = new ArrayList();
list.add(starts);
initPathSet.add(list);
currentPath.put(starts, initPathSet);
}
}
stepList = new ArrayList<Step>();
stepIndex = new HashMap<String, Integer>();
this.isPathEnabled = setPathEnabled;
this.isParallel = setParallel;
this.loopCount = 0;
listElementClass = null;
this.collection = collection;
}
@Override
public long delete(String statement, Object parameter) {
if (logger.isDebugEnabled()) {
logger.debug("Execute 'delete' mongodb command. Statement '" + statement + "'.");
}
DeleteConfig config = (DeleteConfig) configuration.getStatement(statement);
if (config == null) {
throw new MongoDaoException(statement, "Delete statement id '" + statement + "' not found.");
}
String collection = config.getCollection();
NodeEntry query = config.getQuery();
MongoDatabase db = getDatabase();
MongoCollection<Document> coll = db.getCollection(collection).withWriteConcern(WriteConcern.ACKNOWLEDGED);
Map<String, Object> q = (Map<String, Object>) query.executorNode(config.getNamespace(), configuration, parameter);
Document filter = new Document(q);
if (logger.isDebugEnabled()) {
logger.debug("Execute 'delete' mongodb command. Query '" + filter + "'.");
}
DeleteResult result = coll.deleteMany(filter);
if (!result.wasAcknowledged()) {
throw new MongoDaoException(statement, "Execute 'delete' mongodb command has exception. The write was unacknowledged.");
}
return result.getDeletedCount();
}
private Document getDocument(String key, String value) {
MongoCollection<Document> collection = context.getDatabaseManager()
.getCollection(collectionName);
Document doc = collection.find(new BasicDBObject(key, value))
.first();
return doc;
}
public static void main(String[] args) {
MongoClient client = new MongoClient("localhost", 27017);
MongoDatabase friends = client.getDatabase("friends");
MongoCollection relatives = friends.getCollection("relatives");
Bson bson = Sorts.ascending("fname");
FindIterable<Document> docs = relatives.find().sort(bson);
int num = 0;
for (Document doc : docs) {
String name = doc.getString("fname");
String relation = doc.getString("relation");
System.out.printf("%4d. %s, %s%n", ++num, name, relation);
}
}
public Document getMinMax(MongoCollection<Document> mongoCollection, String field, boolean min){
try {
final int sort = min?1:-1;
return mongoCollection.find().sort(new BasicDBObject(field, sort)).projection(new BasicDBObject(field, 1)).first();
} catch (Exception e) {
LOG.error("error while getting field '{}' from mongodb", field, e);
}
return null;
}