MongoDB - 字段更新操作符:$set、$unset、$inc、$currentDate、$rename

文章目录

    • [1. 测试数据构造](#1. 测试数据构造)
    • [2. $set](#2. $set)
      • [2.1 更新字段的值](#2.1 更新字段的值)
      • [2.2 新增字段的值](#2.2 新增字段的值)
      • [2.3 更新嵌入式文档字段的值](#2.3 更新嵌入式文档字段的值)
      • [2.4 更新数组字段的元素值](#2.4 更新数组字段的元素值)
    • [3. $unset](#3. $unset)
    • [4. $currentDate](#4. $currentDate)
    • [5. $inc](#5. $inc)
      • [5.1 更新字段的值](#5.1 更新字段的值)
      • [5.2 新增字段的值](#5.2 新增字段的值)
      • [5.3 递增多个字段值](#5.3 递增多个字段值)
    • [6. $rename](#6. $rename)

更新操作符是用于更新MongoDB文档中字段值的特殊操作符:

$currentDate:将字段的值设置为当前日期或当前时间戳,可以使用该操作符来更新现有字段或创建新字段。
$inc:将字段的值增加指定的数值。如果字段不存在,则创建该字段并设置初始值为指定的数值。
$min:如果字段的值大于指定的值,则将字段的值更新为指定的值。
$max:如果字段的值小于指定的值,则将字段的值更新为指定的值。
$mul:将字段的值乘以指定的数值。如果字段不存在,则创建该字段并设置初始值为0。
$rename:重命名字段。
$set:设置字段的值。如果字段不存在,则创建该字段并设置初始值为指定的值。
$setOnInsert:仅在插入文档时设置字段的值。如果文档已存在,则不会对字段进行更新。
$unset:删除字段。

1. 测试数据构造

json 复制代码
db.student.insertMany([
    {
        name: "Alice",
        age: 25,
        email: "Alice@example.com",
        details: { height: 175, weight: 150 },
        hobbies: ["reading", "writing", "music"],
        course: [
            { subject: "math", score: 90 },
            { subject: "english", score: 80 }
        ]
    },
    {
        name: "John",
        age: 30,
        email: "John@qq.com",
        details: { height: 178, weight: 180 },
        hobbies: ["reading", "gaming", "traveling"],
        course: [
            { subject: "math", score: 70 },
            { subject: "english", score: 80 }
        ]
    },
    {
        name: "Jane",
        age: 25,
        email: "Jane@qq.com",
        details: { height: 160, weight: 100 },
        hobbies: ["sports", "music", "cooking"],
        course: [
            { subject: "math", score: 70 },
            { subject: "english", score: 60 }
        ]
    }
])
java 复制代码
@AllArgsConstructor
@NoArgsConstructor
@Data
@Document(collection = "student")
public class Student {
    @Id
    private String Id;
    private String name;
    private Integer age;
    private String email;
    private Details details;
    private List<String> hobbies;
    private List<Course> course;

    @Data
    public static class Details {
        private Integer height;
        private Integer weight;
    }

    @Data
    public static class Course {
        private String subject;
        private Integer score;
    }
}

2. $set

$set 用于更新文档中的字段值或添加新字段,如果指定多个字段值对,$set 将更新或创建每个字段。

mysql 复制代码
db.collection.update(
   <query>,
   { $set: { <field1>: <value1>, ... } }
)

2.1 更新字段的值

查询 student 集合中 name=Alice 的第一个文档,将 email 字段的值更新为 Alice@163.com ,age 字段的值更新为 20:

mysql 复制代码
db.user.updateOne(
    { name: "Alice" },
    { $set: { age: 20, email: "Alice@163.com" } }
)

db.student.findOne( { name: "Alice" } )
java 复制代码
@Test
public void updateUser(){
    // 创建查询条件
    Criteria criteria = Criteria.where("name").is("Alice");
    // 创建查询对象
    Query query = new Query(criteria);
    // 创建更新对象
    Update update = new Update();
    update.set("age",20);
    update.set("email","Alice@163.com");
    // 执行更新操作
    UpdateResult updateResult = mongoTemplate.updateFirst(query, update, Student.class);
    // 执行查询操作
    Student student = mongoTemplate.findOne(query, Student.class);
    System.out.println(student);
}

查询结果:

json 复制代码
{
    "_id": ObjectId("6695aa76cdfcb4377f062e6e"),
    "name": "Alice",
    "age": Int32("20"),
    "email": "Alice@163.com",
    "details": {
        "height": 175,
        "weight": 150
    },
    "hobbies": [
        "reading",
        "writing",
        "music"
    ],
    "course": [
        {
            "subject": "math",
            "score": 90
        },
        {
            "subject": "english",
            "score": 80
        }
    ]
}

2.2 新增字段的值

查询 student 集合中 name=Alice 的第一个文档,新增字段 gender 并将值置为 female:

mysql 复制代码
db.student.updateOne(
    { name: "Alice" },
    { $set: { gender: "female" } }
)

db.student.findOne( { name: "Alice" } )
java 复制代码
@AllArgsConstructor
@NoArgsConstructor
@Data
@Document(collection = "student")
public class Student {
    @Id
    private String Id;
    private String name;
    private Integer age;
    private String email;
    private Details details;
    private List<String> hobbies;
    private List<Course> course;
    private String gender;

    @Data
    public static class Details {
        private Integer height;
        private Integer weight;
    }

    @Data
    public static class Course {
        private String subject;
        private Integer score;
    }
}
java 复制代码
@Test
public void updateUser(){
    // 创建查询条件
    Criteria criteria = Criteria.where("name").is("Alice");
    // 创建查询对象
    Query query = new Query(criteria);
    // 创建更新对象
    Update update = new Update();
    update.set("gender","female");
    // 执行更新操作
    UpdateResult updateResult = mongoTemplate.updateFirst(query, update, Student.class);
    // 执行查询操作
    Student student = mongoTemplate.findOne(query, Student.class);
    System.out.println(student);
}

查询结果:

json 复制代码
{
    "_id": ObjectId("6695aa76cdfcb4377f062e6e"),
    "name": "Alice",
    "age": Int32("20"),
    "email": "Alice@163.com",
    "details": {
        "height": 175,
        "weight": 150
    },
    "hobbies": [
        "reading",
        "writing",
        "music"
    ],
    "course": [
        {
            "subject": "math",
            "score": 90
        },
        {
            "subject": "english",
            "score": 80
        }
    ],
    "gender": "female"
}

2.3 更新嵌入式文档字段的值

查询 student 集合中 name=Alice 的第一个文档,将嵌入式 details 文档中的 weight 字段设置为120:

mysql 复制代码
db.student.updateOne(
	{ name: "Alice" },
	{ $set: { "details.weight": 120} }
)

db.student.findOne( { name: "Alice" } )
java 复制代码
 @Test
 public void updateUser(){
     // 创建查询条件
     Criteria criteria = Criteria.where("name").is("Alice");
     // 创建查询对象
     Query query = new Query(criteria);
     // 创建更新对象
     Update update = new Update();
     update.set("details.weight",120);
     // 执行更新操作
     UpdateResult updateResult = mongoTemplate.updateFirst(query, update, Student.class);
     // 执行查询操作
     Student student = mongoTemplate.findOne(query, Student.class);
     System.out.println(student);
}

查询结果:

json 复制代码
{
    "_id": ObjectId("6695aa76cdfcb4377f062e6e"),
    "name": "Alice",
    "age": Int32("20"),
    "email": "Alice@163.com",
    "details": {
        "height": 175,
        "weight": 120
    },
    "hobbies": [
        "reading",
        "writing",
        "music"
    ],
    "course": [
        {
            "subject": "math",
            "score": 90
        },
        {
            "subject": "english",
            "score": 80
        }
    ],
    "gender": "female"
}

2.4 更新数组字段的元素值

查询 student 集合中 name=Alice 的第一个文档,将hobbies数组中的第一个元素更新为cooking:

mysql 复制代码
db.student.updateOne(
	{ name: "Alice" },
	{ $set: { "hobbies.0": "cooking"} }
)

db.student.findOne( { name: "Alice" } )
java 复制代码
 @Test
 public void updateUser(){
     // 创建查询条件
     Criteria criteria = Criteria.where("name").is("Alice");
     // 创建查询对象
     Query query = new Query(criteria);
     // 创建更新对象
     Update update = new Update();
     update.set("hobbies.0","cooking");
     // 执行更新操作
     UpdateResult updateResult = mongoTemplate.updateFirst(query, update, Student.class);
     // 执行查询操作
     Student student = mongoTemplate.findOne(query, Student.class);
     System.out.println(student);
}

查询结果:

json 复制代码
{
    "_id": ObjectId("6695aa76cdfcb4377f062e6e"),
    "name": "Alice",
    "age": Int32("20"),
    "email": "Alice@163.com",
    "details": {
        "height": 175,
        "weight": 120
    },
    "hobbies": [
        "cooking",
        "writing",
        "music"
    ],
    "course": [
        {
            "subject": "math",
            "score": 90
        },
        {
            "subject": "english",
            "score": 80
        }
    ],
    "gender": "female"
}

3. $unset

$unset 操作符用于删除指定字段:

mysql 复制代码
db.collection.update(
   <query>,
   { $unset: { <field1>: "", <field2>: "", ... } },
   { <options> }
)

要删除age和email字段,可以使用以下命令:

mysql 复制代码
db.user.insertOne({ 
    name: "Alice", 
    age: 25, 
    email: "alice@example.com" 
});
mysql 复制代码
db.user.update(
   {"name": "Alice"},
   { $unset: { age: "", email: ""} }
)

db.user.findOne( { name: "Alice" } )
java 复制代码
@AllArgsConstructor
@NoArgsConstructor
@Data
@Document(collection = "user")
public class User {
    @Id
    private String id;
    private String name;
    private Integer age;
    private String email;
}
java 复制代码
 @Test
 public void updateUser(){
     // 创建查询条件
     Criteria criteria = Criteria.where("name").is("Alice");
     // 创建查询对象
     Query query = new Query(criteria);
     // 创建更新对象
     Update update = new Update();
     update.unset("age");
     update.unset("email");
     // 执行更新操作
     UpdateResult updateResult = mongoTemplate.updateFirst(query, update, User.class);
     // 执行查询操作
     User user = mongoTemplate.findOne(query, User.class);
     System.out.println(user);
}

4. $currentDate

$currentDate 将字段的值设置为当前日期或当前时间戳,可以使用该操作符来更新现有字段或创建新字段。

mysql 复制代码
db.collection.updateOne(
   { <query> },
   { $currentDate: { <field1>: true, <field2>: { $type: "date" } } }
)

$currentDate 操作符可以接受不同的值来设置字段的值:

  • true:将字段的值设置为当前日期和时间。

  • { $type: "date" }:将字段的值设置为当前日期,忽略时间部分。

mysql 复制代码
db.users.updateOne(
   { _id: 1 },
   { $currentDate: { lastModified: true, registrationDate: { $type: "date" } } }
)

users 集合中 _id 为 1 的文档的 lastModified 字段将被设置为当前日期和时间,而 registrationDate 字段将被设置为当前日期,忽略时间部分。

5. $inc

$inc 将字段的值增加指定的数值。如果字段不存在,则创建该字段并设置初始值为指定的数值。

json 复制代码
db.collection.updateOne(
   { <query> },
   { $inc: { <field1>: <amount1>, <field2>: <amount2>, ... } }
)

5.1 更新字段的值

查询 student 集合中 name=Alice 的第一个文档,将 age+5:

mysql 复制代码
db.student.updateOne(
   { name: "Alice" },
   { $inc: { age: 5 } }
)

db.student.findOne( { name: "Alice" } )
java 复制代码
@Test
public void updateUser(){
    // 创建查询条件
    Criteria criteria = Criteria.where("name").is("Alice");
    // 创建查询对象
    Query query = new Query(criteria);
    // 创建更新对象
    Update update = new Update();
    update.inc("age",5);
    // 执行更新操作
    UpdateResult updateResult = mongoTemplate.updateFirst(query, update, Student.class);
    // 执行查询操作
    Student student = mongoTemplate.findOne(query, Student.class);
    System.out.println(student);
}

查询结果:

json 复制代码
{
    "_id": ObjectId("6695aa76cdfcb4377f062e6e"),
    "name": "Alice",
    "age": 25,
    "email": "Alice@163.com",
    "details": {
        "height": 175,
        "weight": 120
    },
    "hobbies": [
        "cooking",
        "writing",
        "music"
    ],
    "course": [
        {
            "subject": "math",
            "score": 90
        },
        {
            "subject": "english",
            "score": 80
        }
    ],
    "gender": "female"
}

5.2 新增字段的值

查询 student 集合中 name=Alice 的第一个文档,如果 amount 字段不存在将会新增该字段:

mysql 复制代码
db.student.updateOne(
   { name: "Alice" },
   { $inc: { amount : 5 } }
)

db.student.findOne( { name: "Alice" } )
java 复制代码
@Data
@Document(collection = "student")
public class Student {
    @Id
    private String Id;
    private String name;
    private Integer age;
    private String email;
    private Details details;
    private List<String> hobbies;
    private List<Course> course;
    private String gender;
    // 新增的字段
    private Integer amount;

    @Data
    public static class Details {
        private Integer height;
        private Integer weight;
    }

    @Data
    public static class Course {
        private String subject;
        private Integer score;
    }
}
java 复制代码
@Test
public void updateUser(){
    // 创建查询条件
    Criteria criteria = Criteria.where("name").is("Alice");
    // 创建查询对象
    Query query = new Query(criteria);
    // 创建更新对象
    Update update = new Update();
    update.inc("amount",5);
    // 执行更新操作
    UpdateResult updateResult = mongoTemplate.updateFirst(query, update, Student.class);
    // 执行查询操作
    Student student = mongoTemplate.findOne(query, Student.class);
    System.out.println(student);
}

查询的结果:

json 复制代码
{
    "_id": ObjectId("66928a18cdfcb4377f062e42"),
    "name": "Alice",
    "age": 30,
    "email": "Alice@example.com",
    "details": {
        "height": 175,
        "weight": 120
    },
    "hobbies": [
        "cooking",
        "writing",
        "music"
    ],
    "course": [
        {
            "subject": "math",
            "score": 90
        },
        {
            "subject": "english",
            "score": 80
        }
    ],
    "gender": "female",
    "amount": 5
}

5.3 递增多个字段值

查询 student 集合中 name=Alice 的第一个文档,将age+5,嵌入式文档details的weight+5:

mysql 复制代码
db.student.updateOne(
   { name: "Alice" },
   { $inc: { age: 2, "details.weight": 5} }
)
java 复制代码
@Test
public void updateUser(){
    // 创建查询条件
    Criteria criteria = Criteria.where("name").is("Alice");
    // 创建查询对象
    Query query = new Query(criteria);
    // 创建更新对象
    Update update = new Update();
    update.inc("age",-2);
    update.inc("details.weight",-5);
    // 执行更新操作
    UpdateResult updateResult = mongoTemplate.updateFirst(query, update, Student.class);
    // 执行查询操作
    Student student = mongoTemplate.findOne(query, Student.class);
    System.out.println(student);
}

查询的结果:

json 复制代码
{
    "_id": ObjectId("6695aa76cdfcb4377f062e6e"),
    "name": "Alice",
    "age": 23,
    "email": "Alice@163.com",
    "details": {
        "height": 175,
        "weight": 115
    },
    "hobbies": [
        "cooking",
        "writing",
        "music"
    ],
    "course": [
        {
            "subject": "math",
            "score": 90
        },
        {
            "subject": "english",
            "score": 80
        }
    ],
    "gender": "female",
    "amount": 5
}

6. $rename

$rename更新字段的名称:

db.collection.update(
   { <query> },
   { $rename: { <field1>: <newName1>, <field2>: <newName2>, ... } }
)

查询 student 集合中 name=Alice 的第一个文档,将name更名为newName,age更名为newAge:

db.student.updateOne(
   { name: "Alice" },
   { $rename: {age: "newAge",name: "newName"} }
)

查询 student 集合中 newName=Alice 的第一个文档:

db.student.findOne({newName:"Alice"})
json 复制代码
{
    "_id": ObjectId("6695dfb6197700004d003dda"),
    "email": "Alice@example.com",
    "details": {
        "height": 175,
        "weight": 150
    },
    "hobbies": [
        "reading",
        "writing",
        "music"
    ],
    "course": [
        {
            "subject": "math",
            "score": 90
        },
        {
            "subject": "english",
            "score": 80
        }
    ],
    "newAge": 25,
    "newName": "Alice"
}

查询 student 集合中name=Alice 的第一个文档:null

相关推荐
只会copy的搬运工8 分钟前
Mycat中间件
数据库·中间件
茶馆大橘12 分钟前
(黑马点评)八、实现签到统计和uv统计
数据库·redis·学习·阿里云·黑马点评
可爱推推1 小时前
头歌数据库系统原理数据模型测试
数据库·头歌
QQ19284999061 小时前
基于STM32无刷直流电机调速蓝牙APP无线监测控制系统
stm32·嵌入式硬件·mongodb
@听风吟2 小时前
力扣之182.查找重复的电子邮箱
大数据·javascript·数据库·sql·leetcode
小纯洁w3 小时前
MySQL 中优化 SQL 语句以提高查询性能
数据库·sql·mysql
xiaomiphone93 小时前
【PostgreSQL教程】PostgreSQL详细介绍
数据库·sql·mysql·postgresql·oracle
Iam傅红雪3 小时前
mysql表逆向实体类
数据库·mysql·adb
凯哥Java4 小时前
优化批处理流程:自定义BatchProcessorUtils的设计与应用
java·数据库·mysql
拉玛干4 小时前
社团周报系统可行性研究-web后端框架对比-springboot,django,gin
数据库·python·spring·golang