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();
}
}
更新完成后,执行:db.students.find().pretty() 。 "type"为 “homework” 的 score 只有一个了,如下图:

参考链接:
下面再来介绍一下,如何为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 更新数组中的元素的更多相关文章
- mongodb对数组中的元素进行查询详解
原文链接:http://blog.csdn.net/renfufei/article/details/78320176 MongoDB中根据数组子元素进行匹配,有两种方式. 使用 “[数组名].[子元 ...
- mongodb更新数组中的所有匹配项
假如集合中有如下数据 { "_id" : ObjectId("4b97e62bf1d8c7152c9ccb74"), "title" : & ...
- MongoDB 学习笔记之 从数组中删除元素和指定数组位置
从数组中删除元素: 从数组中删除单个元素: db.ArrayTest.updateOne({ "name" : "Bill"},{$pop: {"ad ...
- Numpy.frompyfunc()将计算单个值的函数转化为计算数组中每个元素的函数
Numpy.frompyfunc()将计算单个值的函数转化为计算数组中每个元素的函数 不再通过遍历,对数组中的元素进行运算,利用frompyfunc()将计算单个值的函数转化为计算数组中每个元素的函数 ...
- LeetCode - 统计数组中的元素
1. 统计数组中元素总结 1.1 统计元素出现的次数 为了统计元素出现的次数,我们肯定需要一个map来记录每个数组以及对应数字出现的频次.这里map的选择比较有讲究: 如果数据的范围有限制,如:只有小 ...
- 面试题-->写一个函数,返回一个数组中所有元素被第一个元素除的结果
package com.rui.test; import java.util.Random; /** * @author poseidon * @version 1.0 * @date:2015年10 ...
- php 去除数组中重复元素
去除数组中重复元素, 找了下可以一下两个函数 php array_flip()与array_uniqure() $arr = array(…………) ;// 假设有数组包含一万个元素,里面有重复的元素 ...
- 将String类型的二维数组中的元素用FileOutputStream的write方法生成一个文件
将String类型的二维数组中的元素用FileOutputStream的write方法生成一个文件import java.io.File;import java.io.FileOutputStre ...
- 功能要求:定义一个两行三列的二维数组 names 并赋值,使用二重循环输出二维数组中的元素。
功能要求:定义一个两行三列的二维数组 names 并赋值,使用二重循环输出二维数组中的元素 names={{"tom","jack","mike&qu ...
随机推荐
- 自学华为IoT物联网_12 Huawei LiteOS基础架构
点击返回自学华为IoT物流网 自学华为IoT物联网_12 Huawei LiteOS基础架构 一.1个Huawei LiteOS Kernel 1.1 huawei LiteOS Kernel基本框架 ...
- Nginx+Keepalived部署
-----------ReProxy-------------------------Client-----------192.168.56.200 nginx+keepalived 192.168. ...
- 深挖JDK动态代理(二):JDK动态生成后的字节码分析
接上一篇文章深挖JDK动态代理(一)我们来分析一下JDK生成动态的代理类究竟是个什么东西 1. 将生成的代理类编程一个class文件,通过以下方法 public static void transCl ...
- ACM-ICPC 2018 南京赛区网络预赛 J题Sum(线性筛素数)
题目链接:https://nanti.jisuanke.com/t/30999 参考自博客:https://kuangbin.github.io/2018/09/01/2018-ACM-ICPC-Na ...
- 【P2303】Longge的问题
题目大意:求\[\sum\limits_{i=1}^ngcd(n,i)\] 题解:发现 gcd 中有很多是重复的,因此考虑枚举 gcd. \[\sum\limits_{i=1}^ngcd(n,i)=\ ...
- react-native中的动画
先看效果 这个一个渐渐显示的动画,代码如下 import React from 'react'; import { Animated, Text, View } from 'react-native' ...
- 第四篇 - 爬取前程无忧python相关工作
环境:python3 pycharm 模块:requests,xlwt,urllib.request,re 正常三步走: 1.获取源代码 2.匹配源代码,获得目标数据 3.存储到文件中 直接上代 ...
- C语言进阶——Day 1
C语言提高笔记 Day 1 小数据赋给大变量,首位是1则在前面自动补充1,首位是0则在前方自动补充0. 大数据赋给小变量,低位字节对齐,truncate截断,有可能会造成数据丢失. 程序和进程的差别: ...
- poj 1523"SPF"(无向图求割点)
传送门 题意: 有一张联通网络,求出所有的割点: 对于割点 u ,求将 u 删去后,此图有多少个联通子网络: 对于含有割点的,按升序输出: 题解: DFS求割点入门题,不会的戳这里
- bitmap的使用
https://blog.csdn.net/csdnsevenn/article/details/82230049 使用bitmap来解决: 2的32次方大概是42亿个数,所以这么多数中,存在的为1, ...