(MongoDB Java) $push into array
Asked Answered
E

5

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()));
Eaglet answered 15/3, 2013 at 15:44 Comment(0)
A
35
DBObject listItem = new BasicDBObject("scores", new BasicDBObject("type","quiz").append("score",99));
DBObject updateQuery = new BasicDBObject("$push", listItem);
myCol.update(findQuery, updateQuery);
Archuleta answered 15/3, 2013 at 15:47 Comment(3)
thanks! exactly what i was looking for. i tried somthing similar but i think i put .append in the wrong place.Eaglet
i am trying the example but it does not allow me to use "update"..instead asks me for "updateone" with collections object..Wakeful
It's not possible to use 'update'! What's the reason?!Orchestrion
R
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));
Reba answered 29/10, 2016 at 11:28 Comment(2)
This is way underrated! The new driver is so much more intuitive.Brummell
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.Crenelation
B
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);
Bildungsroman answered 15/3, 2013 at 15:53 Comment(1)
very nice sir! its like jongo syntax. really wish i could accept both answers!Eaglet
S
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 ;-)

Scopoline answered 16/3, 2013 at 21:37 Comment(0)
E
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));
Enact answered 22/8, 2018 at 18:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.