下面列出了com.mongodb.DBCollection#findOne ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public void testFindOne() throws UnknownHostException {
MarcMongodbClient client = new MarcMongodbClient("localhost" , 27017, "sub_last_print");
DBCollection collection = client.getCollection("marc");
BasicDBObject doc = createTestObject();
collection.insert(doc);
assertEquals(1, collection.count());
DBObject myDoc = collection.findOne();
assertEquals("MongoDB", myDoc.get("name"));
assertEquals("database", myDoc.get("type"));
assertEquals(1, myDoc.get("count"));
assertEquals(BasicDBObject.class, myDoc.get("info").getClass());
assertEquals(new BasicDBObject("x", 203).append("y", 102), myDoc.get("info"));
assertEquals(203, ((BasicDBObject)myDoc.get("info")).get("x"));
assertEquals(Integer.class, ((BasicDBObject)myDoc.get("info")).get("x").getClass());
System.out.println(myDoc);
collection.remove(new BasicDBObject("name", "MongoDB"));
}
public DBObject selectOne(DBCollection collection) {
DBObject fields = getFields();
DBObject query = getQuery();
DBObject orderByObject = getOrderByObject();
// 日志
log(fields, query, orderByObject);
if (null == fields && null == orderByObject) {
return collection.findOne(query);
} else if (null != fields && null == orderByObject) {
return collection.findOne(query, fields);
} else {
return collection.findOne(query, fields, orderByObject);
}
}
public PrivateStorage update(String collectionName, Map<String, Object> content) throws JsonProcessingException {
DBObject queryById = new BasicDBObject().append(ID, content.get(ID));
DBCollection collectionFor = mongoPrivateStorageTemplate.getCollection(collectionName);
DBObject dbObject = collectionFor.findOne(queryById);
if (!Optional.ofNullable(dbObject).isPresent()) {
return null;
}
content.remove("_id");
dbObject.putAll(content);
DBObject query = new BasicDBObject().append(ID, dbObject.get(ID));
DBCollection collection = mongoPrivateStorageTemplate.getCollection(collectionName);
collection.update(query, dbObject);
return PrivateStorage.builder()
.collectionName(collectionName)
.collectionContent(jsonParsingService.toJsonString(dbObject.toMap()))
.build();
}
public PrivateStorage findById(String collectionName, String id) throws JsonProcessingException {
DBObject query = new BasicDBObject();
query.put(ID, id);
DBCollection collection = mongoPrivateStorageTemplate.getCollection(collectionName);
DBObject object = collection.findOne(query);
if (!Optional.ofNullable(object).isPresent()) {
return null;
}
return PrivateStorage.builder()
.collectionName(collectionName)
.collectionContent(jsonParsingService.toJsonString(object.toMap()))
.build();
}
/**
* Find a DBObject from database using the query. If the ‘fields' argument is null,
* then return the whole document. Otherwise, only returns given fields.
*
* This method uses reflection to convert the result DBObject into given Object.
*
* @param query The query condition
* @param databaseName The database name
* @param namespace The collection namespace
* @param collection The collection name
* @param filterFields The fields that will be returned.
* @return
*/
public static final Object queryObjectFromMongo(DBObject query, String databaseName,
String namespace, String collection, DBObject filterFields) {
DBCollection coll = getDBCollection(databaseName, namespace, collection);
DBObject dbObject = null;
if ( filterFields != null ) {
dbObject = coll.findOne(query, filterFields);
} else {
dbObject = coll.findOne(query);
}
if ( dbObject != null ) {
return constructObject(dbObject);
} else {
return null;
}
}
/**
* Uses the '.+' regexp on featureId to allow for symbols such as slashes in the id
*
* @param featureId String The featureId to make changes to
* @return DBObjet Returns the the features new state if changes were made and returns null if bad JSON was sent
*/
@PUT
@Path("/{product}/{major}.{minor}.{servicePack}/{build}/{featureId:.+}")
@Consumes(MediaType.APPLICATION_JSON)
public Response putFeature(@BeanParam final Coordinates coordinates, @PathParam("featureId") final String featureId,
final BasicDBObject feature) {
feature.put("calculatedStatus", StatusHelper.getFeatureStatus(feature));
final DBCollection collection = this.mongoLegacyDb.getCollection("features");
final BasicDBObject example = coordinates.getReportCoordinatesQueryObject().append("id", featureId);
final DBObject report = collection.findOne(example);
// get the differences/new edits
// Detect if the edits caused a change
feature.put("statusLastEditedBy", LoggedInUserUtil.getLoggedInUser().getDisplay());
feature.put("lastEditOn", new Date());
final BasicDBList edits = updateEdits(feature, report);
feature.put("edits", edits);
updateTestingTips(this.mongoLegacyDb, coordinates, featureId, feature); // save testing tips / strip them out of the document.
updateEnvironmentDetails(this.mongoLegacyDb, coordinates, feature);
collection.save(feature);
Feature.embedTestingTips(feature, coordinates, this.mongoLegacyDb); // rembed testing tips.
return Response.ok(SerializerUtil.serialise(feature))
.build();// pull back feature - will re-include tips that were extracted prior to saving
}
/**
* Delete a user.
*
* @param id The ID of the user to delete.
* @return Nothing.
*/
@DELETE
@Path("/{id}")
public Response deleteUser(@PathParam("id") String id) {
// Validate the JWT. The JWT must be in the 'users' group. We do not check
// to see if the user is deleting their own profile.
try {
validateJWT(new HashSet<String>(Arrays.asList("users")));
} catch (JWTException jwte) {
return Response.status(Status.UNAUTHORIZED)
.type(MediaType.TEXT_PLAIN)
.entity(jwte.getMessage())
.build();
}
// Retrieve the user from the database.
DB database = mongo.getMongoDB();
DBCollection dbCollection = database.getCollection(User.DB_COLLECTION_NAME);
ObjectId dbId = new ObjectId(id);
DBObject dbUser = dbCollection.findOne(dbId);
// If the user did not exist, return an error. Otherwise, remove the user.
if (dbUser == null) {
return Response.status(Status.BAD_REQUEST).entity("The user name was not Found.").build();
}
dbCollection.remove(new BasicDBObject(User.DB_ID, dbId));
return Response.ok().build();
}
/**
* Retrieve a user's profile.
*
* @param id The ID of the user.
* @return The user's profile, as a JSON object. Private fields such as password and salt are not
* returned.
*/
@GET
@Path("/{id}")
@Produces("application/json")
public Response getUser(@PathParam("id") String id) {
// Validate the JWT. The JWT must belong to the 'users' or 'orchestrator' group.
// We do not check if the user is retrieving their own profile, or someone else's.
try {
validateJWT(new HashSet<String>(Arrays.asList("users", "orchestrator")));
} catch (JWTException jwte) {
return Response.status(Status.UNAUTHORIZED)
.type(MediaType.TEXT_PLAIN)
.entity(jwte.getMessage())
.build();
}
// Retrieve the user from the database.
DB database = mongo.getMongoDB();
DBCollection dbCollection = database.getCollection(User.DB_COLLECTION_NAME);
DBObject user = dbCollection.findOne(new ObjectId(id));
// If the user did not exist, return an error. Otherwise, only return the public
// fields (exclude things like the password).
if (user == null) {
return Response.status(Status.BAD_REQUEST).entity("The user not Found.").build();
}
JsonObject responsePayload = new User(user).getPublicJsonObject();
return Response.ok(responsePayload, MediaType.APPLICATION_JSON).build();
}
@RequestMapping(value = "/api/{projectId}/entities/{name}/{id}", method = RequestMethod.GET, headers = "Accept=application/json")
public @ResponseBody
String getEntityDataById(@PathVariable("projectId") String projectId, @PathVariable("name") String entityName,
@PathVariable("id") String entityDataId,
@RequestHeader(value = "authToken", required = false) String authToken) {
JSONObject authRes = authService.authorize(projectId,authToken,"USER");
if(!authRes.getBoolean(SUCCESS)){
return authRes.toString(4);
}
DBCollection dbCollection = mongoTemplate.getCollection(projectId+"_"+entityName);
BasicDBObject queryObject = new BasicDBObject();
queryObject.append("_id", new ObjectId(entityDataId));
DBObject resultObject = dbCollection.findOne(queryObject);
if(resultObject == null){
return "Not Found";
}
if(entityName.equals("User")){
resultObject.removeField(PASSWORD);
}
dbRefToRelation(resultObject);
String json = resultObject.toString();
// Indentation
JSONObject jsonObject = new JSONObject(json);
return jsonObject.toString(4);
}
@GET
@Path("/{product}")
@Produces(MediaType.APPLICATION_JSON)
public Response getFavouriteStateOfProduct(@PathParam("product") final String product) {
final DBCollection collection = this.mongoLegacyDb.getCollection("users");
final BasicDBObject query = new BasicDBObject("user_id", LoggedInUserUtil.getLoggedInUser().getUserId());
query.put("favourites." + product, true);
final DBObject favState = collection.findOne(query);
return Response.ok(favState != null).build();
}
@GET
@Path("/{product}/{major}.{minor}.{servicePack}/{build}/{featureId}")
@Produces(MediaType.APPLICATION_JSON)
public Response getPresence(@BeanParam final Coordinates coordinates, @PathParam("featureId") final String featureId) {
final DBCollection collection = this.mongoLegacyDb.getCollection("presence");
final BasicDBObject query = new BasicDBObject("coordinates",
coordinates.getObject(Field.PRODUCT, Field.VERSION, Field.BUILD).append(
"featureId", featureId))
.append("_id", coordinates.getProduct() + "/" + coordinates.getVersionString() + "/" + coordinates
.getBuild() + "/" + featureId);
final DBObject newPresence = collection.findOne(query);
newPresence.put("currentUser", LoggedInUserUtil.getLoggedInUser().getDisplay());
return Response.ok(SerializerUtil.serialise(newPresence)).build();
}
@GET
@Path("/{product}")
public Response getEnvironmentsForProduct(@PathParam("product") final String product) {
final DBCollection collection = this.mongoLegacyDb.getCollection("environments");
final DBObject rtn = collection.findOne(new BasicDBObject("coordinates.product", product));
return Response.ok(SerializerUtil.serialise(rtn)).build();
}
/** @return The {@link DBObject} representing the object with the given id */
public static DBObject getById(AbstractMongoDBServer entity, String id) {
LOG.info("Getting {} from {}", new Object[]{id, entity});
MongoClient mongoClient = clientForServer(entity);
// Secondary preferred means the driver will let us read from secondaries too.
mongoClient.setReadPreference(ReadPreference.secondaryPreferred());
try {
DB db = mongoClient.getDB(TEST_DB);
DBCollection testCollection = db.getCollection(TEST_COLLECTION);
return testCollection.findOne(new BasicDBObject("_id", new ObjectId(id)));
} finally {
mongoClient.close();
}
}
@PUT
@Path("/comments/{product}/{major}.{minor}.{servicePack}/{build}/{featureId:.+}")
@Consumes(MediaType.APPLICATION_JSON)
public Response updateCommentWithPatch(@BeanParam final Coordinates coordinates, @PathParam("featureId") final String featureId,
final BasicDBObject patch) {
try {
final DBCollection collection = this.mongoLegacyDb.getCollection("features");
final BasicDBObject example = coordinates.getReportCoordinatesQueryObject().append("id", featureId);
final BasicDBObject storedFeature = (BasicDBObject) collection.findOne(example);
final String scenarioId = (String) patch.get("scenarioId");
final String label = (String) patch.get("label");
final String content = (String) patch.get("content");
final BasicDBObject featureToUpdate = (BasicDBObject) storedFeature.copy();
final BasicDBObject scenarioToUpdate = getScenarioById(scenarioId, featureToUpdate);
scenarioToUpdate.put(label, content);
if (label.equals("testing-tips")) {
final DBCollection tips = this.mongoLegacyDb.getCollection("testingTips");
updateTestingTipsForScenario(tips, scenarioToUpdate, coordinates, featureId);
}
featureToUpdate.put("statusLastEditedBy", LoggedInUserUtil.getLoggedInUser().getDisplay());
featureToUpdate.put("lastEditOn", new Date());
featureToUpdate.put("calculatedStatus", calculateStatusForFeature(featureToUpdate));
collection.save(featureToUpdate);
if (label.equals("testing-tips")) {
Feature.embedTestingTips(featureToUpdate, coordinates, this.mongoLegacyDb);
}
return Response.ok().build();
} catch (final Throwable th) {
th.printStackTrace();
return Response.serverError().build();
}
}
@PUT
@Path("/step/{product}/{major}.{minor}.{servicePack}/{build}/{featureId:.+}")
@Consumes(MediaType.APPLICATION_JSON)
public Response updateStepWithPatch(@BeanParam final Coordinates coordinates, @PathParam("featureId") final String featureId,
final BasicDBObject patch) {
try {
final DBCollection collection = this.mongoLegacyDb.getCollection("features");
final BasicDBObject example = coordinates.getReportCoordinatesQueryObject().append("id", featureId);
final BasicDBObject storedFeature = (BasicDBObject) collection.findOne(example);
final int stepLine = (int) patch.get("line");
final String status = (String) patch.get("status");
final String scenarioId = (String) patch.get("scenarioId");
final BasicDBObject featureToUpdate = (BasicDBObject) storedFeature.copy();
final BasicDBObject scenarioToUpdate = getScenarioById(scenarioId, featureToUpdate);
boolean found = false;
if (scenarioToUpdate.get("background") != null) {
final BasicDBObject backgroundToUpdate = (BasicDBObject) (scenarioToUpdate.get("background"));
final BasicDBList backgroundStepsToUpdate = (BasicDBList) (backgroundToUpdate.get("steps"));
found = updateSteps(backgroundStepsToUpdate, stepLine, status);
}
if (!found) {
final BasicDBList stepsToUpdate = (BasicDBList) (scenarioToUpdate.get("steps"));
updateSteps(stepsToUpdate, stepLine, status);
}
featureToUpdate.put("statusLastEditedBy", LoggedInUserUtil.getLoggedInUser().getDisplay());
featureToUpdate.put("lastEditOn", new Date());
featureToUpdate.put("calculatedStatus", calculateStatusForFeature(featureToUpdate));
collection.save(featureToUpdate);
return Response.ok().build();
} catch (final Throwable th) {
th.printStackTrace();
return Response.serverError().build();
}
}
/**
* Update an existing user.
*
* @param id The ID of the user to update.
* @param payload The fields of the user that should be updated.
* @return Nothing.
*/
@PUT
@Path("/{id}")
@Consumes("application/json")
public Response updateUser(@PathParam("id") String id, JsonObject payload) {
// Validate the JWT. The JWT should be in the 'users' group. We do not
// check to see if the user is modifying their own profile.
try {
validateJWT(new HashSet<String>(Arrays.asList("users")));
} catch (JWTException jwte) {
return Response.status(Status.UNAUTHORIZED)
.type(MediaType.TEXT_PLAIN)
.entity(jwte.getMessage())
.build();
}
// Retrieve the user from the database.
DB database = mongo.getMongoDB();
DBCollection dbCollection = database.getCollection(User.DB_COLLECTION_NAME);
DBObject oldDbUser = dbCollection.findOne(new ObjectId(id));
if (oldDbUser == null) {
return Response.status(Status.BAD_REQUEST).entity("The user was not Found.").build();
}
// If the input object contains a new password, need to hash it for use in the database.
User newUser = null;
if (payload.containsKey("password")) {
try {
String rawPassword = payload.getString("password");
String saltString = (String) (oldDbUser.get(User.JSON_KEY_USER_PASSWORD_SALT));
PasswordUtility pwUtil = new PasswordUtility(rawPassword, saltString);
JsonObject newJson =
createJsonBuilder(payload)
.add(User.JSON_KEY_USER_PASSWORD_HASH, pwUtil.getHashedPassword())
.add(User.JSON_KEY_USER_PASSWORD_SALT, pwUtil.getSalt())
.build();
newUser = new User(newJson);
} catch (Throwable t) {
return Response.serverError().entity("Error updating password").build();
}
} else {
newUser = new User(payload);
}
// Create the updated user object. Only apply the fields that we want the
// client to change (skip the internal fields).
DBObject updateObject = new BasicDBObject("$set", newUser.getDBObjectForModify());
dbCollection.findAndModify(oldDbUser, updateObject);
return Response.ok().build();
}
@Override
public DBObject getChannelConfiguration(String feedName, String channelName) {
DBCollection configColl = getChannelConfigCollection(feedName);
return configColl.findOne(new BasicDBObject("_id", channelName));
}
/**
* 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();
}
/**
* Find a DBObject from database using the query. If the ‘fields' argument is null,
* then return the whole document. Otherwise, only returns given fields.
*
* @param query The query condition
* @param databaseName The database name
* @param namespace The collection namespace
* @param collection The collection name
* @param fields The fields that will be returned.
* @return
*/
public static final DBObject queryFromMongo(DBObject query, String databaseName,
String namespace, String collection, DBObject fields) {
DBCollection coll = getDBCollection(databaseName, namespace, collection);
if ( fields != null ) {
return coll.findOne(query, fields);
} else {
return coll.findOne(query);
}
}
/**
* Find a DBObject from database using the query. If the ‘fields' argument is null,
* then return the whole document. Otherwise, only returns given fields.
*
* @param query The query condition
* @param databaseName The database name
* @param namespace The collection namespace
* @param collection The collection name
* @param fields The fields that will be returned.
* @return
*/
public static final DBObject queryFromMongo(DBObject query, String databaseName,
String namespace, String collection, DBObject fields) {
DBCollection coll = getDBCollection(databaseName, namespace, collection);
if ( fields != null ) {
return coll.findOne(query, fields);
} else {
return coll.findOne(query);
}
}