(MongoDB Java) $push into array

后端 未结 5 526

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:<

相关标签:
5条回答
  • 2020-11-28 10:10
    DBObject listItem = new BasicDBObject("scores", new BasicDBObject("type","quiz").append("score",99));
    DBObject updateQuery = new BasicDBObject("$push", listItem);
    myCol.update(findQuery, updateQuery);
    
    0 讨论(0)
  • 2020-11-28 10:13

    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));
    
    0 讨论(0)
  • 2020-11-28 10:16

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

    0 讨论(0)
  • 2020-11-28 10:19

    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));
    
    0 讨论(0)
  • 2020-11-28 10:20

    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);
    
    0 讨论(0)
提交回复
热议问题