Java Code Examples for com.mongodb.DBCollection#remove()

The following examples show how to use com.mongodb.DBCollection#remove() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MarcMongodbClientTest.java    From metadata-qa-marc with GNU General Public License v3.0 6 votes vote down vote up
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"));
}
 
Example 2
Source File: MarcMongodbClientTest.java    From metadata-qa-marc with GNU General Public License v3.0 6 votes vote down vote up
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());
}
 
Example 3
Source File: EntityDataController.java    From restfiddle with Apache License 2.0 6 votes vote down vote up
@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;
   }
 
Example 4
Source File: MarcMongodbClientTest.java    From metadata-qa-marc with GNU General Public License v3.0 5 votes vote down vote up
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());
}
 
Example 5
Source File: SimpleChannel.java    From hvdf with Apache License 2.0 5 votes vote down vote up
@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));
}
 
Example 6
Source File: ServerIntegrationTest.java    From dropwizard-mongo with Apache License 2.0 5 votes vote down vote up
@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());

}
 
Example 7
Source File: MongoDBUtil.java    From gameserver with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example 8
Source File: MongoDBUtil.java    From gameserver with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
	}
	
}
 
Example 9
Source File: MongoUtil.java    From gameserver with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example 10
Source File: MongoUtil.java    From gameserver with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
	}
	
}
 
Example 11
Source File: AdminUtils.java    From XBDD with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example 12
Source File: AdminUtils.java    From XBDD with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example 13
Source File: PrivateStorageRepository.java    From konker-platform with Apache License 2.0 5 votes vote down vote up
public void remove(String collectionName, String id) {
       DBObject query = new BasicDBObject();
       query.put(ID, id);

       DBCollection collection = mongoPrivateStorageTemplate.getCollection(collectionName);
       collection.remove(query);
}
 
Example 14
Source File: TestProjectResource.java    From scava with Eclipse Public License 2.0 5 votes vote down vote up
@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();
}
 
Example 15
Source File: DeleteVo.java    From tangyuan2 with GNU General Public License v3.0 5 votes vote down vote up
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();
}
 
Example 16
Source File: UserResource.java    From sample-acmegifts with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * 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();
}
 
Example 17
Source File: MongoExample.java    From tutorials with MIT License 4 votes vote down vote up
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);
    }
 
Example 18
Source File: EntityAuthService.java    From restfiddle with Apache License 2.0 3 votes vote down vote up
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;
   }