5

I am trying to insert objects of user-defined class in java into mongodb collection.

My class is like this:

class C extends ReflectionDBObject
{
    int i;
    C(){}
}

and the code for insertion is

Mongo m = new Mongo("localhost");
com.mongodb.DB appdb = m.getDB("appdb");
DBCollection cmpcol = appdb.getCollection("feed");
DBObject bdbo = new BasicDBObject();
C c = new C();
c.i = 1;
bdbo.put("a",c);
cmpcol.insert(bdbo);

But on insertion the object is represented by a null value in the database. What am I doing wrong??I dont want to use gson or morphia.

1 Answer 1

13

The Java driver uses getter and setter methods (not variables) on a ReflectionDBObject class to determine the properties to include in the document.

Hence your code should be:

public class C extends ReflectionDBObject
{
    int i;

    public int geti()
    {
        return i;
    }

    public void seti(int i)
    {
        this.i = i;
    }
}

This will result in an object such as the following in the collection:

{ "_id" : ObjectId("504567d903641896aa40bde6"), "a" : { "_id" : null, "i" : 1 } }

I am not aware of a means of getting rid of the "_id" : null in the sub-document. This is a characteristic of the ReflectionDBObject class. Sub-documents do not usually have _ids, but if you want a non-null _id for the subdocument, you can put the following code in your C() constructor:

public C()
{
    set_id(ObjectId.get());
}

This will result in an object such as the following:

{ 
  "_id" : ObjectId("504568ff0364c2a4a975b375"), 
  "a" : { "_id" : ObjectId("504568ff0364c2a4a975b374"), "i" : 1 } 
}

Finally, note that the geti() and seti() convention for a property "i" is slightly unusual. The JavaBeans spec says that you need getI() and setI() methods to have a property "i". However the MongoDB driver doesn't work that way for the ReflectionDBObject class.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.