Search code examples
javamongodbmorphia

In Morphia how can i update one embedded Object inside an ArrayList


Really new to Using Mongodb with Morphia and see many advanced answers how to do this.

I want to do it simple if it's possible and I have this @Embedded Object called
fileObjects that contains Files Objects.

I Cannot update the fields inside the Files.

I want to update only one field f.ex the String fileHash.

@Entity
public class BatchData {

    @Id private ObjectId id;
    @Embedded
    public ArrayList<Files> fileObjects = new ArrayList<Files>();
}

UPDATE.. Reading the wiki at Morphia Updating dont "really" say how to do this only when the array contains Integer like this:

  @Embedded
   List<Integer> roomNumbers = new ArrayList<Integer>();

Here is what i try so far:

mongo.createUpdateOperations(BatchData.class).add("fileObjects", Files, false);

The Files that this code insert is already in the mongo. The false don't detect that and insert it at the end of the array. Can i add an unique-id to the Files so it detect that the Files am inserting exist in the array, and then just update it?

@Embedded 
public class Files
{ 
    public Files() {

    }

    public int position;
    public String fileName = "";
    public String fileHash = "";

    public Files(int pos, String fileName, String fileHash) {
        this.position = pos;
        this.fileName = fileName;
        this.fileHash = fileHash;
    }
} 

Reading other answers like morphia-mongodb-accessing but he already have the
@Entity BlogEntry(see link) in a POJO outside of mongo. Maybe i have to do the same?
Pull it out, change it and save it back?


Solution

  • Answering my own question for anyone's delight.

    I think i solved it not sure.
    It looks like it's working im testing when the fileObjects have many Files.
    The right fileHash is updated indeed.

    UpdateOperations<BatchData>updateOperations=mongo.createUpdateOperations
                 (BatchData.class)
                .disableValidation().set("fileObjects.$.fileHash",hash).enableVali..;
    
    mongo.update(mongo.createQuery(BatchData.class)
                .filter("uuid",theBatch.uuid)
                .filter("fileObjects.fileName","theFileName"),updateOperations);