系列文章目录
提示:这里可以添加系列文章的所有文章的目录,目录需要自己手动添加
例如:第一章 Python 机器学习入门之pandas的使用
提示:写完文章后,目录可以自动生成,如何生成可参考右边的帮助文档
文章目录
前言
提示:这里可以添加本文要记录的大概内容:
例如:随着人工智能的不断发展,机器学习这门技术也越来越重要,很多人都开启了学习机器学习,本文就介绍了机器学习的基础内容。
提示:以下是本篇文章正文内容,下面案例可供参考
更新
三个基本函数
- db.collection.updateOne(, , )
- db.collection.updateMany(, , )
- db.collection.replaceOne(, , )
其中指查询条件,是指更新操作符
1.更新单个文档
# 更新item值为paper的第一个文档,$set更新操作符,$currentDate表示更新lastModified字段,如果该字段不存在,会生成该字段
db.inventory.updateOne(
{ item: "paper" },
{
$set: { "size.uom": "cm", status: "P" },
$currentDate: { lastModified: true }
}
)
2.行为
原子性
MongoDB的write操作对单一文档来说是原子性的。
id字段
不能变更id字段,也不能用不同id的document来做replace操作
field order
- id字段总是第一个
- renaming field会导致字段顺序变更
使用Aggregation pipeline更新
从4.2开始,可以使用aggregation pipeline做更新操作,pipeline包含如下阶段
- $addFields
- $set
- $project
- $unset
- $replaceRoot
- $replaceWith
updateOperator
Field
- $currentDate
{ $currentDate: { : , … } }
是boolean或 { $type: “timestamp” }{ $type: “date” }
如果字段不存在就新增db.customers.updateOne( { _id: 1 }, { $currentDate: { lastModified: true, "cancellation.date": { $type: "timestamp" } }, $set: { "cancellation.reason": "user request", status: "D" } }
)
```java
@Test
public void TestCurrentDate(){
template.updateFirst(
Query.query(Criteria.where(Fields.UNDERSCORE_ID).is(1))
,new Update()
.currentDate("last")
.currentDate("cancellation.date")
,"customers"
);
List<JSONObject> list2 = template.find(new Query(),JSONObject.class,"customers");
System.out.println(
JSONObject.toJSONString(list2)
);
}
aggretaion Pipeline
- 每个阶段对输入的documents做一次处理操作。
- 一个阶段的输出作为后一个阶段的输入
- 可以对文章分组的结果可以返回。比如平均值,最大值,最小值。
计算订单总量
db.orders.aggregate( [
// Stage 1: Filter pizza order documents by pizza size
{
$match: { size: "medium" }
},
// Stage 2: Group remaining documents by pizza name and calculate total quantity
{
$group: { _id: "$name", totalQuantity: { $sum: "$quantity" } }
}
] )
@Test
public void testCalculateTotalOrderQuantity() {
AggregationResults<JSONObject> results = template.aggregate(
Aggregation.newAggregation(
Aggregation.match(Criteria.where("size").is("medium"))
, Aggregation.group(Fields.fields("$name")).sum("$quantity").as("totalQuantity")
)
, Order.class, JSONObject.class);
System.out.println(
String.format("数量:%d,结果:%s", results.getMappedResults().size(), JSONObject.toJSONString(results.getMappedResults()))
);
}
计算订单总价值,和订单平均数量
db.orders.aggregate( [
// Stage 1: Filter pizza order documents by date range
{
$match:
{
"date": { $gte: new ISODate( "2020-01-30" ), $lt: new ISODate( "2022-01-30" ) }
}
},
// Stage 2: Group remaining documents by date and calculate results
{
$group:
{
_id: { $dateToString: { format: "%Y-%m-%d", date: "$date" } },
totalOrderValue: { $sum: { $multiply: [ "$price", "$quantity" ] } },
averageOrderQuantity: { $avg: "$quantity" }
}
},
// Stage 3: Sort documents by totalOrderValue in descending order
{
$sort: { totalOrderValue: -1 }
}
] )
AggregationResults<JSONObject> results = template.aggregate(
Aggregation.newAggregation(
Aggregation.match(Criteria.where("date").gte(LocalDate.of(2020, 1, 30)).lt(LocalDate.of(2022, 1, 30)))
, Aggregation.addFields().addFieldWithValueOf("date",DateOperators.DateToString.dateOf("$date").toString("%Y-%m-%d")).build()
, Aggregation.group("date")
.sum(ArithmeticOperators.Multiply.valueOf("$price").multiplyBy("$quantity")).as("totalOrderValue")
.avg("$quantity").as("averageOrderQuantity")
, Aggregation.sort(Sort.Direction.DESC,"totalOrderValue")
)
, Order.class, JSONObject.class);
System.out.println(
String.format("数量:%d,结果:%s", results.getMappedResults().size(), JSONObject.toJSONString(results.getMappedResults()))
);