(MongoDB Java)$ push into array [英] (MongoDB Java) $push into array

查看:405
本文介绍了(MongoDB Java)$ push into array的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用mongo 2.2.3和java驱动程序。
我的困境,我必须将一个字段和值推入一个数组,但我似乎无法弄清楚如何做到这一点。我的数据样本:

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
    }
]

我可以推进外壳:

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

但是当我把它翻译成java时,我迷惑了自己并将键盘放在墙上。

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

我的java代码(不完整和错误)到目前为止:

my java code (incomplete and wrong) so far:

DBObject find = new BasicDBObject("_id", 1);
DBObject push = new BasicDBObject("$push", new BasicDBObject(
                        "scores", new BasicDBObject()));


推荐答案

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

这篇关于(MongoDB Java)$ push into array的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆