Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(MongoDB Java) $push into array

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()));
like image 431
notorious.no Avatar asked Mar 15 '13 15:03

notorious.no


People also ask

How do I push data into an array in MongoDB?

If the value is an array, $push appends the whole array as a single element. To add each element of the value separately, use the $each modifier with $push . For an example, see Append a Value to Arrays in Multiple Documents. For a list of modifiers available for $push , see Modifiers.

How do I update an array in MongoDB?

Learn how to update array fields in documents in MongoDB collections. You can use the updateOne() or updateMany() methods to add, update, or remove array elements based on the specified criteria. It is recommended to use the updateMany() method to update multiple arrays in a collection.

How do I add an array of strings in MongoDB?

ArrayList<String> stringArray = new ArrayList<String>(); BasicDBObject document = new BasicDBObject(); document. put("master", stringArray); db. getCollection("master"). insert(document);

How do I update a nested array in MongoDB?

Update Nested Arrays in Conjunction with $[]The $[<identifier>] filtered positional operator, in conjunction with the $[] all positional operator, can be used to update nested arrays. The following updates the values that are greater than or equal to 8 in the nested grades. questions array if the associated grades.


2 Answers

DBObject listItem = new BasicDBObject("scores", new BasicDBObject("type","quiz").append("score",99)); DBObject updateQuery = new BasicDBObject("$push", listItem); myCol.update(findQuery, updateQuery); 
like image 191
Lucas Zamboulis Avatar answered Sep 22 '22 22:09

Lucas Zamboulis


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));
like image 42
trinity Avatar answered Sep 23 '22 22:09

trinity