zoukankan      html  css  js  c++  java
  • MongoDB 更新数组中的元素

     本文记录如何更新MongoDB Collection 中的Array 中的元素。假设Collection中一条记录格式如下:

    现要删除scores 数组中,"type" 为 "homework",较小的那个score。在上图中,较小的score为54.759...

    根据MongoDB上的update用法如下:

    db.collection.update(query, update, options)

    其中,query表示:更新的条件,update表示:待更新的内容,options表示:更新选项(比如,条件不匹配时,进行插入)

    在这里,我们的更新条件为 "_id" 是否匹配;使用 $pull 来删除scores 数组中,"type" 为 "homework",较小的那个score。关于 $pull 的解释如下:

    The $pull operator removes from an existing array all instances of a value or values that match a specified condition.

    比如下面一条语句:更新 "_id" 为1 且将 votes数组中 大于等于6的所有vote 都删除。

    #{ _id: 1, votes: [ 3, 5, 6, 7, 7, 8 ] }
    db.profiles.update( { _id: 1 }, { $pull: { votes: { $gte: 6 } } } 
    #{ _id: 1, votes: [  3,  5 ] }

    其实,从这里可以发现一 点:Mongodb命令中的 {} 相当于JAVA中的 Document对象。  因此,我们的更新实现如下:

    Document updateQuery = new Document("_id", document.get("_id"));//更新条件
    
    //待更新的内容
    Bson update = new Document("scores", new Document("type", "homework").append("score", homework_score_low));
    collection.updateOne(updateQuery, new Document("$pull", update));

    整个完整代码实现如下:

    import com.mongodb.MongoClient;
    import com.mongodb.MongoClientURI;
    import com.mongodb.client.MongoCollection;
    import com.mongodb.client.MongoCursor;
    import com.mongodb.client.MongoDatabase;
    import org.bson.Document;
    import org.bson.conversions.Bson;
    
    import java.util.List;
    
    /**
     * Created by Administrator on 2017/11/2.
     */
    public class HomeWorkScore {
    
        public static void main(String[] args) {
            MongoClient mongoClient = new MongoClient(new MongoClientURI("mongodb://localhost"));
            MongoDatabase database = mongoClient.getDatabase("school");
            MongoCollection<Document> collection = database.getCollection("students");
            MongoCursor<Document> cursor = collection.find().iterator();
            while (cursor.hasNext()) {
                Document document = cursor.next();
                Document updateQuery = new Document("_id", document.get("_id"));//更新条件
                List<Document> scores = (List<Document>) document.get("scores");
                double homework_score_low, home_work_score_high;
                home_work_score_high = scores.get(2).getDouble("score");
                homework_score_low = scores.get(3).getDouble("score");
                if (home_work_score_high < homework_score_low) {
                    homework_score_low = home_work_score_high;
                }
                //待更新的内容
                Bson update = new Document("scores", new Document("type", "homework").append("score", homework_score_low));
                collection.updateOne(updateQuery, new Document("$pull", update));
                System.out.println(document);
            }
            cursor.close();
        }
    }
    View Code

     更新完成后,执行:db.students.find().pretty() 。  "type"为 “homework” 的 score 只有一个了,如下图:

    参考链接:

    update 方法官方文档

    $pull 操作符官方文档

    下面再来介绍一下,如何为Collection中的空Array,添加元素。比如,一条初始的记录如下:comments是个Array,现在要为Array添加Document

    这里需要用到 update 操作中的 $push 操作符:The $push operator appends a specified value to an array. update()的第一个参数是更新条件,第二个参数是更新内容。一个典型的 $push 示例如下:

    db.students.update(
       { _id: 1 },
       { $push: { scores: 89 } }
    )

    将 _id 为1 的记录中的 scores 数组,再添加一个元素89。

    Document comment = new Document("author", name).append("body", body).append("email", email);
    
    postsCollection.updateOne(query, new Document("$push", new Document("comments", comment)));

    更新之后的记录为:

    关于$push,可参考:$push

    从上面介绍可看出,push是新增内容,如果要更新Document中的某个字段的内容(比如更新某个Document中的List中的某个Key所对应的Value),可使用 set。可参考:$set官方文档

    总结:这篇文章是MongoDB University M101 for Java Developers中的第三章 Homework。MongoDB 区别于其他关系型数据库的一个重要特征是:PreJoin。当需要联合多个字段时,Mysql需要Join,而MongoDB则是在预先设计数据存储时 就以 PreJoin的形式 Embedded 所有相关的字段,从而在查询获取数据的时候不需要Join操作了。

    当需要对 MongoDB Collection 中的记录进行操作时,多Google,不需要去记 更新、删除等操作。比如Google:mongodb add element to array ,就能找到如何往一个Array中添加Element

    另外使用Mongo Import 可以导入JSON格式的数据,假设images.json 文件内容如下:

    { "_id" : 0, "height" : 480, "width" : 640, "tags" : [ "dogs", "work" ] }
    { "_id" : 1, "height" : 480, "width" : 640, "tags" : [ "cats", "sunrises", "kittens", "travel", "vacation", "work" ] }
    { "_id" : 2, "height" : 480, "width" : 640, "tags" : [ "dogs", "kittens", "work" ] }

    使用如下命令导入:

    mongoimport --drop -d students -c grades images.json

    原文:http://www.cnblogs.com/hapjin/p/7776595.html

  • 相关阅读:
    前端常用代码
    前端常用代码
    Velocity模版自定义标签
    算法思想
    java特性之三--多态性
    非线性数据结构--图
    接口
    java特性之四--抽象
    (数据结构与算法) 堆
    数据结构_平衡二叉树(AVL树)
  • 原文地址:https://www.cnblogs.com/hapjin/p/7776595.html
Copyright © 2011-2022 走看看