Question

I'm using mongo 2.2.3 and the java driver. My dilemma, I have to $push a field and value into an array, but I cant seem to figure out how to do this. A sample of my data:

"_id" : 1,
"scores" : [
    {
        "type" : "homework",
        "score" : 78.97979
    },
    {
        "type" : "homework",
        "score" : 6.99
    },
    {
        "type" : "quiz",
        "score" : 99
    }
]

I can $push in the shell:

db.collection.update({_id:1},{$push:{scores:{type:"quiz", score:99}}})

but it's when I translate this into java I confuse my self and chuck my keyboard at a wall.

my java code (incomplete and wrong) so far:

DBObject find = new BasicDBObject("_id", 1);
DBObject push = new BasicDBObject("$push", new BasicDBObject(
                        "scores", new BasicDBObject()));
Was it helpful?

Solution

DBObject listItem = new BasicDBObject("scores", new BasicDBObject("type","quiz").append("score",99));
DBObject updateQuery = new BasicDBObject("$push", listItem);
myCol.update(findQuery, updateQuery);

OTHER TIPS

Since mongodb-driver 3.1. there is a builder class com.mongodb.client.model.Updates with appropriate methods for each update case. In this case this would be:

Document score = new Document().append("type", "quiz")
                               .append("score",99);

collection.updateOne(eq("_id", "1"),Updates.addToSet("scores", score));

If you're more comforable with the query format of the shell, you may find it's easier to use JSON.parse to contstruct your DBObject for the $push:

import com.mongodb.util.JSON;

String json = "{$push:{scores:{type:'quiz', score:99}}}";
DBObject push = (DBObject) JSON.parse(json);

Using Jongo, you can do as in the shell:

db.collection.update({_id:1},{$push:{scores:{type:"quiz", score:99}}})

Becomes in Java:

collection.update("{_id:1}").with("{$push:{scores:{type:#, score:#}}}", "quiz", 99);

No fancy DBObject needed ;-)

MongoDB Java driver can simplify this. Use $each instead of $push.

$each mongodb reference document

Java sample -

    BasicDBObject addressSpec = new BasicDBObject();
    addressSpec.put("id", new ObjectId().toString());
    addressSpec.put("name", "one");

    BasicDBObject addressSpec2 = new BasicDBObject();
    addressSpec2.put("id", new ObjectId().toString());
    addressSpec2.put("name", "two");

    List<BasicDBObject> list = new ArrayList<>();
    list.add(addressSpec); list.add(addressSpec2);

    UpdateResult updateOne = individualCollection.updateOne(Filters.eq("_id", "5b7c6b612612242a6d34ebb6"), 
            Updates.pushEach("subCategories", list));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top