下面列出了com.mongodb.DBCollection#find ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private Map<String, Float> readDistanceScores(String startingObject, Set<String> others) {
Map<String, Float> result = new HashMap<String, Float>();
Query query = new org.springframework.data.mongodb.core.query.Query();
query.addCriteria(Criteria.where("type.name").is(_SIMILARITY_METHOD).orOperator(
Criteria.where("fromArtifact.$id").is(new ObjectId(startingObject)),
Criteria.where("toArtifact.$id").is(new ObjectId(startingObject))));
DBCollection dbCollection = mongoTemplate.getCollection("relation");
DBCursor cursor = dbCollection.find(query.getQueryObject());
List<DBObject> list = cursor.toArray();
for (DBObject dbObject : list) {
String toArtifact = ((DBRef) dbObject.get("toArtifact")).getId().toString();
String fromArtifact = ((DBRef) dbObject.get("fromArtifact")).getId().toString();
double value = ((double) dbObject.get("value"));
if (toArtifact.equals(startingObject)) {
if (others.contains(fromArtifact))
result.put(fromArtifact, (float) (1 - value));
} else if (others.contains(toArtifact))
result.put(toArtifact, (float) (1 - value));
}
return result;
}
@Test
public void testMongodbLocalServer() throws Exception {
MongoClient mongo = new MongoClient(mongodbLocalServer.getIp(), mongodbLocalServer.getPort());
DB db = mongo.getDB(propertyParser.getProperty(ConfigVars.MONGO_DATABASE_NAME_KEY));
DBCollection col = db.createCollection(propertyParser.getProperty(ConfigVars.MONGO_COLLECTION_NAME_KEY),
new BasicDBObject());
col.save(new BasicDBObject("testDoc", new Date()));
LOG.info("MONGODB: Number of items in collection: {}", col.count());
assertEquals(1, col.count());
DBCursor cursor = col.find();
while(cursor.hasNext()) {
LOG.info("MONGODB: Document output: {}", cursor.next());
}
cursor.close();
}
private Map<String, Map<String, DataColumn>> generateTableMetaData() {
int ordinalPosition = 1;
Map<String, Map<String, DataColumn>> metaData = new HashMap<>();
HashMap<String, DataColumn> column = new HashMap<>();
for (String tableName : this.tableList) {
DBCollection readResult = jongo.getDatabase().getCollection(tableName);
Iterator<DBObject> cursor = readResult.find();
while (cursor.hasNext()) {
DBObject doumentData = cursor.next();
String tempValue = doumentData.toString();
Iterator<?> keys = new JSONObject(tempValue).keys();
while (keys.hasNext()) {
String columnName = (String) keys.next();
DataColumn dataColumn = new DataColumn(columnName, DataColumn.ODataDataType.STRING,
ordinalPosition, true, 100, columnName.equals(DOCUMENT_ID));
column.put(columnName, dataColumn);
ordinalPosition++;
}
metaData.put(tableName, column);
}
}
return metaData;
}
@Override
public List<T> results(){
DBObject projection;
if(fieldsSpecified){
projection = fields;
}else{
projection = dao.getKeyFields();
}
DBCollectionFindOptions options = new DBCollectionFindOptions();
options.projection(projection);
if(maxTimeMS > 0){
options.maxTime(maxTimeMS, TimeUnit.MILLISECONDS);
}
if(orderBy != null){
options.sort(SortUtil.getSort(orderBy));
}
if(pageNumber>0 && pageSize>0){
options.skip((pageNumber-1) * pageSize);
options.limit(pageSize);
}
DBCollection coll = dao.getCollection();
DBCursor cursor = coll.find(condition, options);
return MapperUtil.toList(dao.getEntityClass(), cursor, withoutCascade);
}
private Map<String, Float> readDistanceScores(String object) {
Map<String, Float> result = new HashMap<String, Float>();
Query query = new org.springframework.data.mongodb.core.query.Query();
query.addCriteria(Criteria.where("type.name").is(_SIMILARITY_METHOD).orOperator(
Criteria.where("fromArtifact.$id").is(new ObjectId(object)),
Criteria.where("toArtifact.$id").is(new ObjectId(object))));
DBCollection dbCollection = mongoTemplate.getCollection("relation");
DBCursor cursor = dbCollection.find(query.getQueryObject());
List<DBObject> list = cursor.toArray();
for (DBObject dbObject : list) {
String toArtifact = ((DBRef) dbObject.get("toArtifact")).getId().toString();
String fromArtifact = ((DBRef) dbObject.get("fromArtifact")).getId().toString();
double value = ((double) dbObject.get("value"));
if (toArtifact.equals(object))
result.put(fromArtifact, (float) (1 - value));
else
result.put(toArtifact, (float) (1 - value));
}
return result;
}
private Map<String, Float> readDistanceScores(String object) {
Map<String, Float> result = new HashMap<String, Float>();
Query query = new org.springframework.data.mongodb.core.query.Query();
query.addCriteria(Criteria.where("type.name").is(sm.getSimilarityName()).orOperator(
Criteria.where("fromArtifact.$id").is(new ObjectId(object)),
Criteria.where("toArtifact.$id").is(new ObjectId(object))));
DBCollection dbCollection = mongoTemplate.getCollection("relation");
DBCursor cursor = dbCollection.find(query.getQueryObject());
List<DBObject> list = cursor.toArray();
for (DBObject dbObject : list) {
String toArtifact = ((DBRef) dbObject.get("toArtifact")).getId().toString();
String fromArtifact = ((DBRef) dbObject.get("fromArtifact")).getId().toString();
double value = ((double) dbObject.get("value"));
if (toArtifact.equals(object))
result.put(fromArtifact, (float) (1 - value));
else
result.put(toArtifact, (float) (1 - value));
}
return result;
}
/**
* Execute a query on (mongo) database
*
* @param query path to query
* @param type type of data in query (string or json)
* @param collection collection in database
* @param modifications modifications to perform in query
*/
@When("^I execute a query '(.+?)' of type '(json|string)' in mongo '(.+?)' database using collection '(.+?)' with:$")
public void sendQueryOfType(String query, String type, String database, String collection, DataTable modifications) throws Exception {
try {
commonspec.setResultsType("mongo");
String retrievedData = commonspec.retrieveData(query, type);
String modifiedData = commonspec.modifyData(retrievedData, type, modifications);
commonspec.getMongoDBClient().connectToMongoDBDataBase(database);
DBCollection dbCollection = commonspec.getMongoDBClient().getMongoDBCollection(collection);
DBObject dbObject = (DBObject) JSON.parse(modifiedData);
DBCursor cursor = dbCollection.find(dbObject);
commonspec.setMongoResults(cursor);
} catch (Exception e) {
commonspec.getExceptions().add(e);
}
}
private JSONArray getJSONArrayFromDB(String db, String col) {
try {
JSONArray result = new JSONArray();
DBCollection collection = mongo.getDB(db).getCollectionFromString(col);
DBCursor cursor = collection.find();
while(cursor.hasNext()) {
DBObject obj = cursor.next();
JSONObject json = new JSONObject(JSON.serialize(obj));
result.put(json);
}
return result;
}
catch(Exception e) {
System.out.println("We got an error when creating a JSONArray: " + e);
return null;
}
}
/**
* Get all user profiles.
*
* @return All user profiles (excluding private fields like password).
*/
@GET
@Produces("application/json")
public Response getAllUsers() {
// Validate the JWT. The JWT must be in the 'users' group.
try {
validateJWT(new HashSet<String>(Arrays.asList("users")));
} catch (JWTException jwte) {
return Response.status(Status.UNAUTHORIZED)
.type(MediaType.TEXT_PLAIN)
.entity(jwte.getMessage())
.build();
}
// Get all the users from the database, and add them to an array.
DB database = mongo.getMongoDB();
DBCollection dbCollection = database.getCollection(User.DB_COLLECTION_NAME);
DBCursor cursor = dbCollection.find();
JsonArrayBuilder userArray = Json.createArrayBuilder();
while (cursor.hasNext()) {
// Exclude all private information from the list.
userArray.add((new User(cursor.next()).getPublicJsonObject()));
}
// Return the user list to the caller.
JsonObjectBuilder responseBuilder = Json.createObjectBuilder().add("users", userArray.build());
return Response.ok(responseBuilder.build(), MediaType.APPLICATION_JSON).build();
}
@GET
@Path("/product/{product}/{major}.{minor}.{servicePack}/{build}")
@Produces(MediaType.APPLICATION_JSON)
public Response getProductHistory(@BeanParam final Coordinates coordinates) {
List<String> buildList = new ArrayList<>();
final DBCollection collection = this.mongoLegacyDb.getCollection("summary");
final DBObject productQuery = coordinates.getQueryObject(Field.PRODUCT, Field.MAJOR, Field.MINOR, Field.SERVICEPACK);
final DBCursor results = collection.find(productQuery);
while (results.hasNext()) {
buildList = (List<String>) results.next().get("builds");
}
final DBCollection featureCollection = this.mongoLegacyDb.getCollection("features");
final List<BasicDBObject> buildDBObjectList = new ArrayList<>();
for (final String build : buildList) {
coordinates.setBuild(build);
final DBObject buildQuery = coordinates.getQueryObject();
final BasicDBObject buildObj = new BasicDBObject();
buildObj.put("passed", getNumberOfState(featureCollection, buildQuery, "passed"));
buildObj.put("failed", getNumberOfState(featureCollection, buildQuery, "failed"));
buildObj.put("skipped", getNumberOfState(featureCollection, buildQuery, "skipped"));
buildObj.put("undefined", getNumberOfState(featureCollection, buildQuery, "undefined"));
buildObj.put("name", build);
buildDBObjectList.add(buildObj);
}
return Response.ok(SerializerUtil.serialise(buildDBObjectList)).build();
}
@Test
public void in() throws Exception {
UUID appId = emf.lookupApplication( "test-organization/test-app" );
EntityManager em = emf.getEntityManager( appId );
Map<String, Object> properties = new LinkedHashMap<String, Object>();
properties.put( "name", "Kings of Leon" );
properties.put( "genre", "Southern Rock" );
properties.put( "founded", 2000 );
em.create( "testin", properties );
properties = new LinkedHashMap<String, Object>();
properties.put( "name", "Stone Temple Pilots" );
properties.put( "genre", "Rock" );
properties.put( "founded", 1986 );
em.create( "testin", properties );
properties = new LinkedHashMap<String, Object>();
properties.put( "name", "Journey" );
properties.put( "genre", "Classic Rock" );
properties.put( "founded", 1973 );
em.create( "testin", properties );
// See http://www.mongodb.org/display/DOCS/Java+Tutorial
Mongo m = new Mongo( "localhost", 27017 );
DB db = m.getDB( "test-organization/test-app" );
db.authenticate( "test", "test".toCharArray() );
BasicBSONList list = new BasicBSONList();
list.add( "Stone Temple Pilots" );
list.add( "Journey" );
BasicDBObject query = new BasicDBObject();
query.put( "name", new BasicDBObject( "$in", list ) );
DBCollection coll = db.getCollection( "testins" );
DBCursor cur = coll.find( query );
assertTrue( cur.hasNext() );
DBObject result = cur.next();
assertEquals( "Journey", result.get( "name" ) );
assertEquals( "Classic Rock", result.get( "genre" ) );
result = cur.next();
assertEquals( "Stone Temple Pilots", result.get( "name" ) );
assertEquals( "Rock", result.get( "genre" ) );
assertFalse( cur.hasNext() );
}
@Override
public void transactionMarker() {
DB database = mongoClient.getDB("testdb");
DBCollection collection = database.getCollection("test");
collection.find();
}
@ResponseBody
@RequestMapping(value="/getMgmtCmdResult.do")
public Map<String, Object> getMgmtCmdResult(HttpServletRequest request) throws Exception {
Map<String, Object> response = new HashMap<String, Object>();
HttpSession session = request.getSession(false);
if(session != null){
//페이지 권한 확인
GroupAuthorization requestAuth = (GroupAuthorization) session.getAttribute("requestAuth");
if(!requestAuth.getAuthorizationDBRead().equals("1")){
response.put("result", 1);
response.put("errorCode", -1);
response.put("content", "authMessage: onem2m 페이지 접근 권한이 없습니다.");
} else {
String collection = HeritProperties.getProperty("Globals.MongoDB.Collection");
DBCollection col = db.getCollection(collection);
String rn = request.getParameter("rn");
if (rn == null || rn.equals("")) {
response.put("result", 1);
response.put("errorCode", -1);
response.put("content", "parameters[rn] is missing");
}
BasicDBObject query = new BasicDBObject();
query.put("ty", 8);
query.put("ext", rn);
DBCursor cursor = col.find(query);
List<DBObject> dbObjList = new ArrayList<DBObject>();
try {
while (cursor.hasNext()) {
dbObjList.add(cursor.next());
////System.out.println("############# dbObjList.toString() = " + dbObjList.toString());
}
} finally {
cursor.close();
}
response.put("result", 0);
response.put("errorCode", 0);
response.put("content", dbObjList.toString());
}
} else {
response.put("result", 1);
response.put("errorCode", -1);
response.put("content", "session is null");
}
return response;
}
/**
* Uses the '.+' regexp on featureId to allow for symbols such as slashes in the id
*
* @param featureId String The featureId to get the history for
* @return DBObjet Returns the past feature status for the given featureId
*/
@GET
@Path("/rollup/{product}/{major}.{minor}.{servicePack}/{featureId:.+}")
@Produces(MediaType.APPLICATION_JSON)
public Response getFeatureRollup(@BeanParam final Coordinates coordinates, @PathParam("featureId") final String featureId) {
final List<BasicDBObject> features = new ArrayList<>();
final DBCollection collection = this.mongoLegacyDb.getCollection("features");
final DBCollection summary = this.mongoLegacyDb.getCollection("summary");
final BasicDBObject example = coordinates.getRollupQueryObject(featureId);
final DBCursor cursor = collection.find(example,
new BasicDBObject("id", 1).append("coordinates.build", 1).append("calculatedStatus", 1)
.append("originalAutomatedStatus", 1).append("statusLastEditedBy", 1));
try {
while (cursor.hasNext()) {
final DBObject doc = cursor.next();
final BasicDBObject rollup = new BasicDBObject()
.append("build", ((DBObject) doc.get("coordinates")).get("build"))
.append("calculatedStatus", doc.get("calculatedStatus"))
.append("originalAutomatedStatus", doc.get("originalAutomatedStatus"))
.append("statusLastEditedBy", doc.get("statusLastEditedBy"));
features.add(rollup);
}
} finally {
cursor.close();
}
final BasicDBObject returns = new BasicDBObject()
.append("coordinates", coordinates.getRollupCoordinates().append("featureId", featureId)
.append("version", coordinates.getVersionString()));
final DBObject buildOrder = summary.findOne(coordinates.getQueryObject());
final List<String> buildArray = (List<String>) buildOrder.get("builds");
final List<BasicDBObject> orderedFeatures = new ArrayList<>();
for (final String build : buildArray) {
for (final BasicDBObject feature : features) {
if (feature.get("build").equals(build)) {
orderedFeatures.add(feature);
break;
}
}
}
returns.append("rollup", orderedFeatures);
return Response.ok(SerializerUtil.serialise(returns)).build();
}
@Test
public void and() throws Exception {
UUID appId = emf.lookupApplication( "test-organization/test-app" );
EntityManager em = emf.getEntityManager( appId );
Map<String, Object> properties = new LinkedHashMap<String, Object>();
properties.put( "name", "Kings of Leon" );
properties.put( "genre", "Southern Rock" );
properties.put( "founded", 2000 );
em.create( "testand", properties );
properties = new LinkedHashMap<String, Object>();
properties.put( "name", "Stone Temple Pilots" );
properties.put( "genre", "Rock" );
properties.put( "founded", 1986 );
em.create( "testand", properties );
properties = new LinkedHashMap<String, Object>();
properties.put( "name", "Journey" );
properties.put( "genre", "Classic Rock" );
properties.put( "founded", 1973 );
em.create( "testand", properties );
// See http://www.mongodb.org/display/DOCS/Java+Tutorial
Mongo m = new Mongo( "localhost", 27017 );
DB db = m.getDB( "test-organization/test-app" );
db.authenticate( "test", "test".toCharArray() );
BasicBSONList list = new BasicBSONList();
list.add( new BasicDBObject( "founded", new BasicDBObject( "$gte", 2000 ) ) );
list.add( new BasicDBObject( "founded", new BasicDBObject( "$lte", 2005 ) ) );
BasicDBObject query = new BasicDBObject();
query.put( "$and", list );
DBCollection coll = db.getCollection( "testands" );
DBCursor cur = coll.find( query );
assertTrue( cur.hasNext() );
DBObject result = cur.next();
assertEquals( "Kings of Leon", result.get( "name" ) );
assertEquals( "Southern Rock", result.get( "genre" ) );
assertFalse( cur.hasNext() );
}
@Test
public void lessThan() throws Exception {
UUID appId = emf.lookupApplication( "test-organization/test-app" );
EntityManager em = emf.getEntityManager( appId );
Map<String, Object> properties = new LinkedHashMap<String, Object>();
properties.put( "name", "Kings of Leon" );
properties.put( "genre", "Southern Rock" );
properties.put( "founded", 2000 );
em.create( "lessthan", properties );
properties = new LinkedHashMap<String, Object>();
properties.put( "name", "Stone Temple Pilots" );
properties.put( "genre", "Rock" );
properties.put( "founded", 1986 );
em.create( "lessthan", properties );
properties = new LinkedHashMap<String, Object>();
properties.put( "name", "Journey" );
properties.put( "genre", "Classic Rock" );
properties.put( "founded", 1973 );
em.create( "lessthan", properties );
// See http://www.mongodb.org/display/DOCS/Java+Tutorial
Mongo m = new Mongo( "localhost", 27017 );
DB db = m.getDB( "test-organization/test-app" );
db.authenticate( "test", "test".toCharArray() );
BasicDBObject query = new BasicDBObject();
query.put( "founded", new BasicDBObject( "$lt", 2000 ) );
DBCollection coll = db.getCollection( "lessthans" );
DBCursor cur = coll.find( query );
assertTrue( cur.hasNext() );
DBObject result = cur.next();
assertEquals( "Journey", result.get( "name" ) );
assertEquals( "Classic Rock", result.get( "genre" ) );
result = cur.next();
assertEquals( "Stone Temple Pilots", result.get( "name" ) );
assertEquals( "Rock", result.get( "genre" ) );
assertFalse( cur.hasNext() );
}
@ResponseBody
@RequestMapping(value="/getMgmtCmdResult.do")
public Map<String, Object> getMgmtCmdResult(HttpServletRequest request) throws Exception {
Map<String, Object> response = new HashMap<String, Object>();
HttpSession session = request.getSession(false);
if(session != null){
//페이지 권한 확인
GroupAuthorization requestAuth = (GroupAuthorization) session.getAttribute("requestAuth");
if(!requestAuth.getAuthorizationDBRead().equals("1")){
response.put("result", 1);
response.put("errorCode", -1);
response.put("content", "authMessage: onem2m 페이지 접근 권한이 없습니다.");
} else {
String collection = HeritProperties.getProperty("Globals.MongoDB.Collection");
DBCollection col = db.getCollection(collection);
String rn = request.getParameter("rn");
if (rn == null || rn.equals("")) {
response.put("result", 1);
response.put("errorCode", -1);
response.put("content", "parameters[rn] is missing");
}
BasicDBObject query = new BasicDBObject();
query.put("ty", 8);
query.put("ext", rn);
DBCursor cursor = col.find(query);
List<DBObject> dbObjList = new ArrayList<DBObject>();
try {
while (cursor.hasNext()) {
dbObjList.add(cursor.next());
////System.out.println("############# dbObjList.toString() = " + dbObjList.toString());
}
} finally {
cursor.close();
}
response.put("result", 0);
response.put("errorCode", 0);
response.put("content", dbObjList.toString());
}
} else {
response.put("result", 1);
response.put("errorCode", -1);
response.put("content", "session is null");
}
return response;
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*
* Get resource
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if (mDS != MongoService.getInstance()) {
System.out.println("MongoService db name is changed");
mDS = MongoService.getInstance();
mCollRef = mDS.getCollection("refpoints");
mCollSamp = mDS.getCollection("samplings");
mCollMap = mDS.getCollection("maps");
}
String type = request.getParameter("type");
String id = request.getParameter("id");
System.out.println("doGet: type=" + type + " id=" + id);
if ("file".equals(type)) {
if (id == null) {
// Get list of files
mDS.sendJSON(mDS.getFileList(), request, response);
return;
}
try {
mDS.sendFile(id, response);
} catch (Exception e) {
System.err.println("Send error: " + id);
}
return;
}
// Get document(s)
String distinct = request.getParameter("distinct");
String pipeline = request.getParameter("pipeline");
String query = request.getParameter("query");
String keys = request.getParameter("keys");
String format = request.getParameter("format");
DBObject queryObj = query != null ? (DBObject) JSON.parse(query) : null;
DBObject keysObj = keys != null ? (DBObject) JSON.parse(keys) : null;
Object result = null;
DBCollection collection = mDS.getCollection(type);
if (id != null) {
result = collection.findOne(new ObjectId(id), keysObj);
} else if (distinct != null) {
result = collection.distinct(distinct, queryObj);
} else if (pipeline != null) {
DBObject pipelineObj = (DBObject) JSON.parse(pipeline);
if (pipelineObj instanceof List<?>) {
result = collection.aggregate((List<DBObject>) pipelineObj).results();
} else {
result = collection.aggregate(pipelineObj).results();
}
} else {
DBCursor cursor = collection.find(queryObj, keysObj);
String sort = request.getParameter("sort");
String skip = request.getParameter("skip");
String limit = request.getParameter("limit");
String count = request.getParameter("count");
if (sort != null) {
cursor = cursor.sort((DBObject) JSON.parse(sort));
}
if (skip != null) {
cursor = cursor.skip(Integer.parseInt(skip));
}
if (limit != null) {
cursor = cursor.limit(Integer.parseInt(limit));
}
result = "true".equals(count) ? cursor.count() : cursor;
}
if (id != null && result == null) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST, String.format("Document %s does not exist", id));
return;
}
if ("csv".equals(format)) {
mDS.sendCSV(result, request, response);
return;
}
mDS.sendJSON(result, request, response);
}
public List<TenantLog> findAll(Tenant tenant) {
List<TenantLog> logs = new ArrayList<>(MAX_DOCUMENTS);
String collectionName = getCollectionName(tenant);
checkCollection(collectionName);
DBCollection collection = mongoAuditTemplate.getCollection(collectionName);
DBCursor cursor = collection.find();
try {
while (cursor.hasNext()) {
cursor.next();
String message = (String) cursor.curr().get("message");
String level = (String) cursor.curr().get("level");
Long time = (Long) cursor.curr().get("time");
logs.add(TenantLog.builder().level(level).message(message).time(new Date(time)).build());
}
} finally {
cursor.close();
}
return logs;
}
public List<PrivateStorage> findAll(String collectionName) throws JsonProcessingException {
List<PrivateStorage> privatesStorage = new ArrayList<>();
DBCollection collection = mongoPrivateStorageTemplate.getCollection(collectionName);
DBCursor cursor = collection.find();
toPrivateStorageList(collectionName, privatesStorage, cursor);
return privatesStorage;
}