在上一章节【练中学,学中练:MongoDB综合查询实战】中,我们通过一系列具体的查询任务,掌握了如何有效地从MongoDB中检索数据。接下来,我们将进一步深化对数据库操作的理解,聚焦于各种运算符的应用,通过综合实践来探索它们如何帮助我们在数据处理中达到更高的灵活性和效率。让我们一起进入运算符的世界,开启新的学习旅程。
知识准备
比较运算符
| 符号 | 含义 | 示例 |
|---|---|---|
$lt | 小于 | {'age': {'$lt': 20}} |
$gt | 大于 | {'age': {'$gt': 20}} |
$lte | 小于等于 | {'age': {'$lte': 20}} |
$gte | 大于等于 | {'age': {'$gte': 20}} |
$ne | 不等于 | {'age': {'$ne': 20}} |
$in | 在范围内 | {'age': {'$in': [20, 23]}} |
$nin | 不在范围内 | {'age': {'$nin': [20, 23]}} |
算术运算符
1、$add
加法运算,基础语法:{ $add : [ < expression1 > , < expression2 > , ... ] }
2、$subtract
减法运算,基础语法:{ $subtract: [ <expression1>, <expression2> ] } expression1减去expression2
3、$multiply
乘法运算,基础语法:{ $multiply : [ < expression1 > , < expression2 > , ... ] }
4、$divide
除法运算,基础语法:{ $divide: [ <expression1>, <expression2> ] }expression1为被除数,expression2为除数
上述4个基础语法中 是需要运算的字段或数字,add 和multiply 的可以多于2个。见例三
注:
1.以上4个都只支持对数字类型的的字段进行运算,字符串类型不可以。
2.Int类型和Double之间可以运算。
3.当 中有一个不存在或为null时,运算结果皆为空。
4.时间(DateTime)可以计算,加减的最终结果是毫秒。
5.若是String类型的时间,需用$dateFromString转换为时间类型在计算。
逻辑运算符
求值运算符
任务要求
1、统计商品的总费用(price + fee)
2、商品的有效日期是在现有的date字段数据 + 3天(注意时间参数的单位为毫秒)。
3、统计出,每个商品的总额(商品价格*商品数据量)
任务准备
例如我们有一个sales的集合, 其中有 商品类别字段、商品价格 字段,商品服务费 字段。
db.sales.insertMany([{
"_id": 1,
"item": "abc",
"price": 10,
"fee": 2,
date: ISODate("2024-03-01 08:00:00Z")
},
{
"_id": 2,
"item": "jkl",
"price": 20,
"fee": 1,
date: ISODate("2024-03-01 09:00:00Z")
},
{
"_id": 3,
"item": "xyz",
"price": 5,
"fee": 0,
date: ISODate("2024-03-15 09:00:00Z")
}]);
任务实施
- 统计商品的总费用(price + fee) 使用 $add 运算符来计算 price 和 fee 的总和。
db.sales.aggregate([ { project: { totalCost: { add: ["fee"] }, item: 1, price: 1, fee: 1, date: 1 } } ]);
- 商品的有效日期是在现有的date字段数据 + 3天 使用 $add 运算符来增加日期。
db.sales.aggregate([ { project: { item: 1, price: 1, fee: 1, date: 1, validDate: { add: ["$date", 259200000] } // 3 days in milliseconds (3 * 24 * 60 * 60 * 1000) } } ]);
- 统计出,每个商品的总额(商品价格 * 商品数量) 这里假设每个商品的数量为1(因为题目中没有提到数量字段),所以总额就是 price。 如果需要计算基于具体数量的数量,则需要添加数量字段。这里我们暂时按照每个商品数量为1的情况来计算。
db.sales.aggregate([ { project: { item: 1, price: 1, fee: 1, date: 1, totalAmount: { multiply: ["$price", 1] } // 假设每个商品数量为1 } } ]);
如果要根据具体数量字段来计算,可以修改为: db.sales.aggregate([ { project: { item: 1, price: 1, fee: 1, date: 1, quantity: 1, // 假设存在数量字段 totalAmount: { multiply: ["quantity"] } } } ]);
附录 数据类型转换
**1、int转换为string类型**
String();
db.collectionName.find().forEach(function(x) {
x.FieldName = x.FieldName.toString();
db.collectionName.save(x);
});
db.emp.find({sal:{$lt:String(2000)}});
2、string转换为Date类型
ISODate()、
db.collectionName.find().forEach(function(x) {
x.FieldName = new ISODate(x.FieldName );
db.collectionName.save(x);
});
3、string转换为int类型
常用有:Number(),NumberInt,NumberLong,NumberDEcimal
//string转为int类型
db.collections.find().forEach( function (x) {
x.ise= NumberInt (x.ise);
db.collections.save(x);
});
4、Mongodb库中已存在的数据的类型转换
db.emp.updateMany({
sal: {
$exists: true
}},
[{$addFields:{
sal: {
$toDouble: "$sal"
}}}]
);