Conversion from String to MongoDB ObjectID

前端 未结 5 1492
情深已故
情深已故 2021-01-20 09:18

I tried converting my String ID to MongoDB ObjectID

public class relevancy_test extends  Object implements Comparable {
    public static voi         


        
5条回答
  •  粉色の甜心
    2021-01-20 10:15

    I am able to convert String to ObjectId like below:

    Here I am updating zip code of 'address' collection, suppose you will get REST api input like below:

    {  
       "id": "5b38a95eb96e09a310a21778",
       "zip":"10012"
    }
    

    Now I have to find address record based on the above mentioned id (which is an ObjectId in mongodb). I have a mongorepository for that, and using below code to find the the Address record:

    @Repository
    public interface AddressRepository extends MongoRepository{
    
    @Query("{'_id': ?0}")
    Address findByObjectId(ObjectId id);
    
    }
    

    And use this repository method in your service class, like:

        public void updateZipCode(Address addressInput){
            Address address = 
    addressRepository.findByObjectId(new ObjectId(addressInput.getId()));
            //here you will get address record based on the id
        }
    

提交回复
热议问题