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 ...
随机推荐
- Codeforces Round #453 (Div. 1) D. Weighting a Tree(构造)
题意 一个 \(n\) 个点 \(m\) 条边的无向连通图中每个点都有一个权值,现在要求给每条边定一个权值,满足每个点的权值等于所有相连的边权之和,权值可负. 题解 如果图是一棵树,那么方案就是唯一的 ...
- UVA 11149-Power of Matrix(等比矩阵求和)
给定一个矩阵A 要求A + A^2 + A^3 +…. A^k: 对于到n的等比矩阵求和 如果n是偶数: 如果n是奇数: #include<stdio.h> #include<s ...
- APIO2018解题报告
今年的APIO好邪啊. T1铁人两项 题目大意 给一个无向图,问有多少三元组(三个元素两两不同)使得它们构成一条简单路径 . 题解 无向图这种东西不好直接处理,考虑点双缩点建圆方树. 然后就出现了一个 ...
- 【docker】docker安装和使用
一.docker简介: docker是容器技术的一个代表,而容器技术是将程序打包和隔离的一种技术,其实它并不是一个新技术,之前在linux内核中早已存在,真正被大众所用所了解是因为docker的出现. ...
- 编写高质量代码:改善Java程序的151个建议 --[26~36]
提防包装类型的null值 public static int testMethod(List<Integer> list) { int count = 0; for (Integer i ...
- js jquery 数组的合并 对象的合并
转载自:http://www.cnblogs.com/xingxiangyi/p/6416468.html 1 数组合并 1.1 concat 方法 1 2 3 4 var a=[1,2,3],b=[ ...
- yd的汇总
因为是我这只蒟蒻个人的汇总嘛,可能有些奇♂怪的东西或者不规范的语言出现啦,见谅见谅 搬了一些到知识汇总里,删了一些过时和无用的,少了好多=.= 1.STL_queue 经实践验证,!qs.empty( ...
- 第十二节、尺度不变特征(SIFT)
上一节中,我们介绍了Harris角点检测.角点在图像旋转的情况下也可以检测到,但是如果减小(或者增加)图像的大小,可能会丢失图像的某些部分,甚至导致检测到的角点发生改变.这样的损失现象需要一种与图像比 ...
- 转:upload.parseRequest为空
上传是items一直是空list.导致原因是struts2把原始的原来S2为简化上传功能,把所有的enctype="multipart/form-data"表单做了wrapper最 ...
- Redis的主从复制的原理介绍
redis主从复制 和Mysql主从复制的原因一样,Redis虽然读取写入的速度都特别快,但是也会产生读压力特别大的情况.为了分担读压力,Redis支持主从复制,Redis的主从结构可以采用一主多从或 ...