36

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()));
0

5 Answers 5

35
DBObject listItem = new BasicDBObject("scores", new BasicDBObject("type","quiz").append("score",99));
DBObject updateQuery = new BasicDBObject("$push", listItem);
myCol.update(findQuery, updateQuery);
Sign up to request clarification or add additional context in comments.

3 Comments

thanks! exactly what i was looking for. i tried somthing similar but i think i put .append in the wrong place.
i am trying the example but it does not allow me to use "update"..instead asks me for "updateone" with collections object..
It's not possible to use 'update'! What's the reason?!
22

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));

2 Comments

This is way underrated! The new driver is so much more intuitive.
Note that the exact equivalent to $push is com.mongodb.client.model.Updates.push which can add duplicates. On the other hand, Updates.addToSet is for simulating a set in which if the element already exists, it isn't inserted.
12

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);

1 Comment

very nice sir! its like jongo syntax. really wish i could accept both answers!
6

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 ;-)

Comments

1

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));

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.