(MongoDB Java) $push into array

醉酒当歌 提交于 2019-11-26 09:36:31

问题


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

回答1:


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



回答2:


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



回答3:


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



回答4:


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




回答5:


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


来源:https://stackoverflow.com/questions/15436542/mongodb-java-push-into-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!