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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM