고객이 여러 주소를 가질 수있는 고객 데이터 로더를 작성 중입니다. 고객을 찾지 못하면 고객 정보를 작성하고 주소를 추가합니다. 고객이있는 경우 다음과 같이 새 주소를 추가하면됩니다.MongoDB에 여러 하위 문서 추가
DBObject findCustomer = new BasicDBObject();
findCustomer.put("email", custEmail);
//check for existing customer
DBObject newCustomer = customerCollection.findOne(findCustomer);
if (newCustomer == null) {
//INSERT
newCustomer = new BasicDBObject();
newCustomer.put("firstname", firstname);
newCustomer.put("lastname", lastname);
newCustomer.put("email", custEmail);
newCustomer.put("password", custData.getPassword());
newCustomer.put("softwaretime", new Date());
}
DBObject newAddress = new BasicDBObject();
City tempCity = new City();
tempCity = addressData.getCity();
newAddress.put("type", addressData.getType());
newAddress.put("line1", addressData.getLine1());
newAddress.put("line2", addressData.getLine2());
newAddress.put("city", tempCity.getCity());
newAddress.put("state", tempCity.getState());
newAddress.put("postal", tempCity.getZip());
newAddress.put("country", tempCity.getCountry());
newCustomer.put("address", newAddress);
customerCollection.save(newCustomer);
이것은 신규 고객에게 유용합니다. 문제는 고객이 이미 존재하면 새 주소가 기존 주소를 덮어 씁니다.
새 주소를 고객에게 추가하여 여러 주소를 유지하려면 어떻게해야합니까?
내가 발견 한 것부터, 나는 이것을 쉘을 통해 "밀어 넣기"로 수행 할 수 있어야합니다. 하지만 BasicDBObject에서 메서드로 "push"하는 것을 보지 못했습니다.
위험한 것처럼 보입니다. 이름과 성이 동일한 고객이 여러 명일 경우 어떻게됩니까? 이 코드는 스레드로부터 안전하지 않습니다. 두 스레드가 동일한 고객을 만들려고하면 중복 될 수 있습니다. 동일한 주소가 두 번 푸시되었을 수도 있습니다. –
좋은 지적 @AsyaKamsky, 대신 검색 키에 이메일 주소를 사용하겠습니다. 또한 MongoDB에 데이터를로드하기 위해 설계된 단일 스레드 응용 프로그램입니다. 여러 (경쟁하는) 스레드가있을 가능성이있는 경우 스레드 안전을 어떻게 고려해야할까요? – Aaron
여러 가지 방법이 있습니다 - 응용 프로그램 논리가 필요로하는 것이 무엇인지에 따라 다릅니다. 전자 메일을 고유하게 만들 수 있으며 두 번째 삽입 시도가 실패하지만 응용 프로그램에서이를 예상하고 복구해야합니다. 자바 동시성을 사용할 수는 있지만 문제가되는 주소의 사본이 여러 개인 경우 $ push 대신 $ addToSet을 사용하면 이미 목록에있는 주소가 추가되지는 않습니다. –