Blue Sky
Blue Sky

Reputation: 827

java mongo arraylist save

We are using a Java server and Mongo DB [plain Java-Mongo and not Morphia or some such tool for the CRUD].
We are having a Image Pojo class and its related Metadata like below,

public class Img{
    private String name;
    private List<Metadata> imgMetaList = new ArrayList<Metadata>();

    //Getters, setters etc...
    public List<Metadata> getImgMetaList() {        
        return imgMetaList;
    }
}

Metadata class has some data, implementing Serializable didn't work, so
i extended ReflectionDBObject,

public class Metadata extends ReflectionDBObject{
    private String tag;
    private String val;

    //Getters, setters etc...      
}

I want to save the Img into Mongo. I used the following code and it worked.

BasicDBObject updateQuery = new BasicDBObject();
updateQuery.put("name", img.getName());
BasicDBObject updMetadata = new BasicDBObject();
updMetadata.put("$push", new BasicDBObject("imgMetaList",img.getImgMetaList()) );
collection.update(updateQuery,updMetadata, true, false);    

This inserts a document in Mongo as below,

{
    "_id" : ObjectId("503a1991db2e9f431cf0d162"),
    "name" : "test.jpg",
    "imgMetaList" : [
        [
            {
                    "Tag" : "tag1",
                    "Val" : "val1",
                    "_id" : null
            }
        ]
    ]
}

Here there are 2 issues,
1. The code is inserting two square brackets instead of one to house the array
2. why isn't the _id getting generated for the list.

Please let me know.
Regards, Vish

Upvotes: 4

Views: 4118

Answers (1)

Ian Daniel
Ian Daniel

Reputation: 606

$push appends a value to an array. If the array does not exist yet, a new array is created. The item you are pushing is an array, so you end up with an array inside an array.

An _id is not being generated for the collection because this is normal behaviour for MongoDB. When you put a sub-document in an document, the sub-document does not get an _id. Hence the array does not have an _id.

Perhaps instead you are asking why your metadata document, inside the array, has a null _id. This is a behaviour of the ReflectionDBObject class: it includes an _id field, but it is up to you to set its value. You can set this _id to a non-null value by calling set_id() on your ReflectionDBObject instance. A good place to do this might be in the constructor of your Metadata class. To generate an _id, use the ObjectId.get() static method (org.bson.types.ObjectId).

Your code for inserting the image in MongoDB is more complicated than it needs to be. The following will work (and will get rid of the nested array):

BasicDBObject imageDoc = new BasicDBObject();
imageDoc("name", img.getName());
imageDoc("imgMetaList", img.getImgMetaList());
collection.insert(imageDoc);

Upvotes: 2

Related Questions