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 ...
随机推荐
- Angular、React.js 和Node.js到底选谁?
为了工作,程序员选择正确的框架和库来构建应用程序是至关重要的,这也就是为什么Angular和React之间有着太多的争议.Node.js的出现,让这场战争变得更加复杂,虽然有选择权通常是一件很棒的事情 ...
- html标题、段落、换行与字符实体
通过 <h1>.<h2>.<h3>.<h4>.<h5>.<h6>,标签可以在网页上定义6种级别的标题.6种级别的标题表示文档的6 ...
- Mysql 允许远程连接
授权的方式允许任何主机访问mysql服务器: mysql>GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'password' W ...
- 定时器同步+触发三ADC采样+输出6路PWM波
为了熟悉定时器定时器和ADC 用STM32F407DIS做了一个简单的工程: 通过高级定时器TIM1溢出更新时间作为触发输出信号(TRGO),触发TIM8开始计数: 同时TIM1的通道1.2.3以及分 ...
- hdu 1686 Oulipo (kmp)
Problem Description The French author Georges Perec (1936–1982) once wrote a book, La disparition, w ...
- hdu 2859 Phalanx (最大对称子矩阵)
Problem Description Today is army day, but the servicemen are busy with the phalanx for the celebrat ...
- lnmp架构搭建实例
lamp->lnmp nginx survey.netcraft.net 查看各大网站使用的web服务器,使用下面的命令 # curl -I www.sina.com 结论:现在大型网站几乎统一 ...
- JS小积累(一)— 判断在线离线
JS小积累-判断在线离线 作者: 狐狸家的鱼 Github: 八至 if(window.navigator.onLine==true){ console.log('online'); ... } el ...
- Linux基本命令总结(一)
java开发的服务器一般都是linux系统,因此把有关命令小结一下: 1,cd [目录名] 进入相应的目录下. cd / 进入系统的根目录 cd .. 或者 cd .. // 退入当前位置的上级目录 ...
- Keyboard Hook API函数 参数说明
来源:https://www.cnblogs.com/grenet/archive/2010/12/07/1898840.html 1.Keyboard的HOOK函数分为两种,WH_KEYBOARD_ ...