-
Type: New Feature
-
Resolution: Done
-
Priority: Major - P3
-
Affects Version/s: None
-
Component/s: None
-
Labels:None
Take some time to think about good ways to offer convenience methods for constructing DBObject trees. Obviously, literal JSON strings is one way, but it doesn't allow the use of program variables.
I offer this as an example:
static public class DBObjBuilder
{
final private LinkedList<DBObject> objStack;
private DBObject top()
public DBObjBuilder()
{ this.objStack = new LinkedList<DBObject>(); }public DBObjBuilder push(DBObject obj)
{ this.objStack.addLast(obj); return this; }public DBObjBuilder push()
{ return push(new BasicDBObject()); }public DBObjBuilder pop(String key)
{ DBObject last = objStack.removeLast(); top().put(key, last); return this; } public DBObjBuilder pop(String... keys)
{
int n = keys.length;
DBObject[] objs = new DBObject[n];
for (int i = n; --i >= 0; )
DBObject _top = top();
for (int i = 0; i < n; ++i)
{ _top.put(keys[i], objs[i]); }
return this;
}
public DBObjBuilder wrap(String key)
{ DBObject last = objStack.removeLast(); DBObject o = new BasicDBObject(); o.put(key, last); return push(o); }
public DBObjBuilder wrap(String... keys)
{
int n = keys.length;
DBObject[] objs = new DBObject[n];
for (int i = n; --i >= 0; )
{ objs[i] = objStack.removeLast(); }
DBObject o = new BasicDBObject();
for (int i = 0; i < n; ++i)
return push(o);
}
public DBObjBuilder set(String key, Object value)
public DBObjBuilder setList(String key, Object... values)
{
BasicDBList l = new BasicDBList();
for (Object value : values)
top().put(key, l);
return this;
}
public DBObject get()
}
This is somewhat like an RPN calculator for constructing DBObjects.
use case:
DBObjBuilder msetBuilder = new DBObjBuilder();
DBObject mset = msetBuilder.push().set("foo",1).set("bar","cleveland").setList("baz",3,"Wombat",44)
.wrap("metadata")
.wrap("$set")
.get();
This creates the equivalent to JSON object {"$set": {"metadata":
{"foo": 1, "bar": "cleveland", "baz", [3, "Wombat", 44]}}}
(running commentary: push() creates a new object on the stack; set() and setList() set a bunch of fields; wrap() pops the top object and sets a value of a new object that gets pushed on the top of the stack; get() returns the top object on the stack)