Thursday, January 23, 2014

MongoDB 2.4 - Mongo and Java (remove a sub-document from a list)

Note: ways to remove a sub-document which is the element of an list

1. document

{
        "_id" : 0,
        "scores" : [
                {
                        "type" : "exam",
                        "score" : 1.463179736705023
                },
                {
                        "type" : "quiz",
                        "score" : 11.78273309957772
                },
                {
                        "type" : "homework",
                        "score" : 6.676176060654615
                },
                {
                        "type" : "homework",
                        "score" : 35.8740349954354
                }
        ]
}

2. $unset

- Mongo: db.students.update({"_id":0},{$unset:{"scores.3":true}})
- Java

collection.update(new BasicDBObject("_id", 0), new BasicDBObject("$unset", new BasicDBObject("scores.3", true)));

- Note: scores.3 will be 'null'

3. $pull

- Mongo: db.students.update({"_id":0},{$pull:{"scores":{"type":"homework","score":35.8740349954354}}})
- Java

collection.update(new BasicDBObject("_id", document.get("_id")),  new BasicDBObject("$pull", new BasicDBObject("scores", new BasicDBObject("type", "homework").append("score", scoreTemp))));

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.