本文记录如何更新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();
}
}

更新完成后,执行: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

MongoDB 更新数组中的元素的更多相关文章

  1. mongodb对数组中的元素进行查询详解

    原文链接:http://blog.csdn.net/renfufei/article/details/78320176 MongoDB中根据数组子元素进行匹配,有两种方式. 使用 “[数组名].[子元 ...

  2. mongodb更新数组中的所有匹配项

    假如集合中有如下数据 { "_id" : ObjectId("4b97e62bf1d8c7152c9ccb74"), "title" : & ...

  3. MongoDB 学习笔记之 从数组中删除元素和指定数组位置

    从数组中删除元素: 从数组中删除单个元素: db.ArrayTest.updateOne({ "name" : "Bill"},{$pop: {"ad ...

  4. Numpy.frompyfunc()将计算单个值的函数转化为计算数组中每个元素的函数

    Numpy.frompyfunc()将计算单个值的函数转化为计算数组中每个元素的函数 不再通过遍历,对数组中的元素进行运算,利用frompyfunc()将计算单个值的函数转化为计算数组中每个元素的函数 ...

  5. LeetCode - 统计数组中的元素

    1. 统计数组中元素总结 1.1 统计元素出现的次数 为了统计元素出现的次数,我们肯定需要一个map来记录每个数组以及对应数字出现的频次.这里map的选择比较有讲究: 如果数据的范围有限制,如:只有小 ...

  6. 面试题-->写一个函数,返回一个数组中所有元素被第一个元素除的结果

    package com.rui.test; import java.util.Random; /** * @author poseidon * @version 1.0 * @date:2015年10 ...

  7. php 去除数组中重复元素

    去除数组中重复元素, 找了下可以一下两个函数 php array_flip()与array_uniqure() $arr = array(…………) ;// 假设有数组包含一万个元素,里面有重复的元素 ...

  8. 将String类型的二维数组中的元素用FileOutputStream的write方法生成一个文件

      将String类型的二维数组中的元素用FileOutputStream的write方法生成一个文件import java.io.File;import java.io.FileOutputStre ...

  9. 功能要求:定义一个两行三列的二维数组 names 并赋值,使用二重循环输出二维数组中的元素。

    功能要求:定义一个两行三列的二维数组 names 并赋值,使用二重循环输出二维数组中的元素 names={{"tom","jack","mike&qu ...

随机推荐

  1. 添加默认安全组规则-openstack

    if [ "$1" ] ;then neutron security-group-rule-create --direction ingress --ethertype ipv4 ...

  2. 面试---Python中的模块和包是什么?

    python模块是: 自我包含并且有组织的代码片段为模块. 表现形式为:写的代码保存为文件.这个文件就是一个模块.sample.py 其中文件名smaple为模块名字. python包是: 包是一个有 ...

  3. Dividing the Path POJ - 2373(单调队列优化dp)

    给出一个n长度的区间,然后有一些小区间只能被喷水一次,其他区间可以喷水多次,然后问你要把这个区间覆盖起来最小需要多少喷头,喷头的半径是[a, b]. 对于每个只能覆盖一次的区间,我们可以把他中间的部分 ...

  4. 【mysql】mysql null值

    在数据表我们有时候有些表字段会为null,表示空.其实在mysql中null值是占用空间的. mysql手册如下解释 NULL columns require additional space in ...

  5. poj 3279 Fliptile(二进制搜索)

    Farmer John knows that an intellectually satisfied cow is a happy cow who will give more milk. He ha ...

  6. POJ--3614 Sunscreen(贪心)

    题目 3614 Sunscreen 2500*2500直接排序暴力贪心 #include<iostream> #include<cstring> #include<alg ...

  7. js 获取 url 参数

    /** * 根据页面地址获取所有参数对象 * @return Object{} 返回所有参数 * ------------------------------ * 根据页面地址获取指定参数对象 * @ ...

  8. 【模板】多项式乘法(FFT)

    题目描述 给定一个n次多项式F(x),和一个m次多项式G(x). 请求出F(x)和G(x)的卷积. 输入输出格式 输入格式: 第一行2个正整数n,m. 接下来一行n+1个数字,从低到高表示F(x)的系 ...

  9. django模板中使用JQ代码实现瀑布流显示效果

    settings中的配置不再详细说明 一.路由代码 from django.contrib import admin from django.conf.urls import url from app ...

  10. request 请求头的处理

    一.请求头:说明了请求要带的一些说明,有的请求需要带,有的不需要带 一般会带上格式,对于新浪微博来说,他一定要带上user-agent content-type:application/json 二. ...