下面列出了com.mongodb.DBCollection#remove ( ) 实例代码,或者点击链接到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 synchronized void testImport() throws URISyntaxException, IOException, InterruptedException {
MarcMongodbClient client = new MarcMongodbClient("localhost" , 27017, "sub_last_print");
DBCollection collection = client.getCollection("marc");
assertEquals(0, collection.count());
boolean insert = true;
if (insert) {
JsonPathCache<? extends XmlFieldInstance> cache;
List<String> records = FileUtils.readLines("general/marc.json");
for (String record : records) {
cache = new JsonPathCache<>(record);
Object jsonObject = jsonProvider.parse(record);
String id = cache.get("$.controlfield.[?(@.tag == '001')].content").get(0).getValue();
String x003 = cache.get("$.controlfield.[?(@.tag == '003')].content").get(0).getValue();
BasicDBObject doc = new BasicDBObject("type", "marcjson")
.append("id", id)
.append("x003", x003)
.append("record", record);
collection.insert(doc);
}
assertEquals(674, collection.count());
}
collection.remove(new BasicDBObject("type", "marcjson"));
assertEquals(0, collection.count());
}
@RequestMapping(value = "/api/{projectId}/entities/{name}/{uuid}", method = RequestMethod.DELETE, headers = "Accept=application/json")
public @ResponseBody
StatusResponse deleteEntityData(@PathVariable("projectId") String projectId, @PathVariable("name") String entityName,
@PathVariable("uuid") String uuid,
@RequestHeader(value = "authToken", required = false) String authToken) {
StatusResponse res = new StatusResponse();
JSONObject authRes = authService.authorize(projectId,authToken,"USER");
if(!authRes.getBoolean(SUCCESS)){
res.setStatus("Unauthorized");
return res;
}
DBCollection dbCollection = mongoTemplate.getCollection(projectId+"_"+entityName);
BasicDBObject queryObject = new BasicDBObject();
queryObject.append("_id", new ObjectId(uuid));
dbCollection.remove(queryObject);
res.setStatus("DELETED");
return res;
}
/**
* 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();
}
public void testInsert() throws UnknownHostException {
MarcMongodbClient client = new MarcMongodbClient("localhost" , 27017, "sub_last_print");
DBCollection collection = client.getCollection("marc");
BasicDBObject doc = createTestObject();
collection.insert(doc);
assertNotNull(collection);
assertEquals(1, collection.count());
collection.remove(new BasicDBObject("name", "MongoDB"));
assertEquals(0, collection.count());
}
public int delete(DBCollection collection, WriteConcern writeConcern) {
DBObject query = new BasicDBObject();
if (null != condition) {
this.condition.setQuery(query, null);
}
log(query);
// WriteResult result = collection.remove(query, WriteConcern.ACKNOWLEDGED);
WriteResult result = collection.remove(query, writeConcern);
// collection.remove(query)
// System.out.println(query.toString());
return result.getN();
}
@Test
public void testPostInsert() throws Exception {
Request request = new Request(Method.POST, "http://localhost:8182/projects/");
ObjectMapper mapper = new ObjectMapper();
ObjectNode p = mapper.createObjectNode();
p.put("name", "test");
p.put("shortName", "test-short");
p.put("description", "this is a description");
request.setEntity(p.toString(), MediaType.APPLICATION_JSON);
Client client = new Client(Protocol.HTTP);
Response response = client.handle(request);
System.out.println(response.getEntity().getText() + " " + response.isEntityAvailable());
validateResponse(response, 201);
// Now try again, it should fail
response = client.handle(request);
validateResponse(response, 409);
// Clean up
Mongo mongo = new Mongo();
DB db = mongo.getDB("scava");
DBCollection col = db.getCollection("projects");
BasicDBObject query = new BasicDBObject("name", "test");
col.remove(query);
mongo.close();
}
public void remove(String collectionName, String id) {
DBObject query = new BasicDBObject();
query.put(ID, id);
DBCollection collection = mongoPrivateStorageTemplate.getCollection(collectionName);
collection.remove(query);
}
@DELETE
@Path("/delete/{product}")
@Produces(MediaType.APPLICATION_JSON)
public Response softDeleteEntireProduct(@PathParam("product") final String product) {
final DBCollection collection = this.mongoLegacyDb.getCollection("summary");
final DBCollection targetCollection = this.mongoLegacyDb.getCollection("deletedSummary");
final BasicDBObject query = new BasicDBObject("coordinates.product", product);
final DBCursor cursor = collection.find(query);
DBObject doc;
while (cursor.hasNext()) {
doc = cursor.next();
// kill the old id
doc.removeField("_id");
try {
targetCollection.insert(doc);
} catch (final Throwable e) {
return Response.status(500).build();
}
}
collection.remove(query);
return Response.ok().build();
}
@DELETE
@Path("/delete/{product}/{version}")
@Produces(MediaType.APPLICATION_JSON)
public Response softDeleteSingleVersion(@PathParam("product") final String product,
@PathParam("version") final String version) {
final DBCollection collection = this.mongoLegacyDb.getCollection("summary");
final DBCollection targetCollection = this.mongoLegacyDb.getCollection("deletedSummary");
final Pattern productReg = java.util.regex.Pattern.compile("^" + product + "/" + version + "$");
final BasicDBObject query = new BasicDBObject("_id", productReg);
final DBCursor cursor = collection.find(query);
DBObject doc;
while (cursor.hasNext()) {
doc = cursor.next();
// kill the old id
doc.removeField("_id");
try {
targetCollection.insert(doc);
} catch (final Throwable e) {
return Response.status(500).build();
}
}
collection.remove(query);
return Response.ok().build();
}
/**
* Delete an object from mongo database.
*
* @param query
* @param databaseName
* @param namespace
* @param collection
* @param isSafeWrite
* @return
*/
public static final void deleteFromMongo(DBObject query, String databaseName,
String namespace, String collection, boolean isSafeWrite) {
DBCollection coll = getDBCollection(databaseName, namespace, collection);
if ( isSafeWrite ) {
coll.remove(query, WriteConcern.SAFE);
} else {
coll.remove(query, WriteConcern.NONE);
}
}
/**
* Remove the given collection from database.
* @param databaseName
* @param namespace
* @param collection
*/
public static final void removeDocument(String databaseName,
String namespace, String collection, DBObject query) {
DBCollection coll = getDBCollection(databaseName, namespace, collection);
if ( query == null ) {
query = MongoUtil.createDBObject();
}
coll.remove(query);
}
/**
* Delete an object from mongo database.
*
* @param query
* @param databaseName
* @param namespace
* @param collection
* @param isSafeWrite
* @return
*/
public static final void deleteFromMongo(DBObject query, String databaseName,
String namespace, String collection, boolean isSafeWrite) {
DBCollection coll = getDBCollection(databaseName, namespace, collection);
if ( isSafeWrite ) {
coll.remove(query, WriteConcern.SAFE);
} else {
coll.remove(query, WriteConcern.NONE);
}
}
/**
* Remove the given collection from database.
* @param databaseName
* @param namespace
* @param collection
*/
public static final void removeDocument(String databaseName,
String namespace, String collection, DBObject query) {
DBCollection coll = getDBCollection(databaseName, namespace, collection);
if ( query == null ) {
query = MongoDBUtil.createDBObject();
}
coll.remove(query);
}
@Before
public void before() {
final DB test = mongoClient.getDB("test");
final DBCollection coll = test.getCollection("test");
coll.remove(new BasicDBObject());
coll.insert(new BasicDBObject());
coll.insert(new BasicDBObject());
}
@Override
public void removeSample(Object sampleId) {
ObjectId oid = (ObjectId)sampleId;
com.mongodb.hvdf.oid.SampleId _id =
idFactory.createId(oid);
DBCollection collection = allocator.getCollection(_id.getTime());
collection.remove(new BasicDBObject(Sample.ID_KEY, oid));
}
public static void main(String[] args) {
MongoClient mongoClient = new MongoClient("localhost", 27017);
DB database = mongoClient.getDB("myMongoDb");
// print existing databases
mongoClient.getDatabaseNames().forEach(System.out::println);
database.createCollection("customers", null);
// print all collections in customers database
database.getCollectionNames().forEach(System.out::println);
// create data
DBCollection collection = database.getCollection("customers");
BasicDBObject document = new BasicDBObject();
document.put("name", "Shubham");
document.put("company", "Baeldung");
collection.insert(document);
// update data
BasicDBObject query = new BasicDBObject();
query.put("name", "Shubham");
BasicDBObject newDocument = new BasicDBObject();
newDocument.put("name", "John");
BasicDBObject updateObject = new BasicDBObject();
updateObject.put("$set", newDocument);
collection.update(query, updateObject);
// read data
BasicDBObject searchQuery = new BasicDBObject();
searchQuery.put("name", "John");
DBCursor cursor = collection.find(searchQuery);
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
// delete data
BasicDBObject deleteQuery = new BasicDBObject();
deleteQuery.put("name", "John");
collection.remove(deleteQuery);
}
public boolean logout(String llt){
DBCollection dbCollection = mongoTemplate.getCollection(ENTITY_AUTH);
BasicDBObject queryObject = new BasicDBObject();
queryObject.append("_id", new ObjectId(llt));
WriteResult result = dbCollection.remove(queryObject);
return result.getN() == 1;
}