您的位置:首页 > 汽车 > 时评 > MongoDB - 数组更新操作符:$、$[]、$pop、$pull、$push、$each、$sort、$slice、$position

MongoDB - 数组更新操作符:$、$[]、$pop、$pull、$push、$each、$sort、$slice、$position

2024/9/8 10:18:35 来源:https://blog.csdn.net/qq_42764468/article/details/140595713  浏览:    关键词:MongoDB - 数组更新操作符:$、$[]、$pop、$pull、$push、$each、$sort、$slice、$position

文章目录

    • 1. $
      • 1. 更新数组中的值
      • 2. 更新数组中的嵌入文档
    • 2. $[]
      • 1. 更新数组中的所有元素
      • 2. 更新数组中的所有嵌入文档
    • 3. $pop
      • 1. 删除数组的第一个元素
      • 2. 删除数组的最后一个元素
    • 4. $pull
      • 1. 删除所有等于指定值的项
      • 2. 删除与指定条件匹配的所有项
      • 3. 从文档数组中删除项
      • 4. 从嵌套数组中删除文档
    • 5. $push
      • 1. $push 将值追加到数组
      • 2. $push 与 $each
      • 3. $push 与 $each 与 $positon
      • 4. $slice
      • 5. $push 与 $slice
      • 6. $push 与 $sort
      • 7. $push 与 $each 与 $position 与 $sort 与 $slice

$:充当占位符,用于更新与查询条件匹配的第一个元素。

$[]:充当占位符,以更新数组中与查询条件匹配的文档中的所有元素。

$[<identifier>]:充当占位符,以更新与查询条件匹配的文档中所有符合 arrayFilters 条件的元素。

$addToSet:类似于 $push,但是只会向数组字段添加不存在的元素。

$pop:用于从数组字段中删除第一个或最后一个元素。

$pull:用于从数组字段中删除符合指定条件的元素。

$push:用于向数组字段添加元素。

$pullAll:用于从数组字段中删除包含在指定数组中的所有元素。

1. $

$ 将数组中匹配到的第一个元素更新为指定的值。

db.collection.updateOne({ <array>: value ... },{ <update operator>: { "<array>.$" : value } }
)

具体解释如下:

  • <update operator>:表示要使用的更新操作符,例如 s e t 、 set、 setinc、$push等。
  • <array>.$”:表示要更新的数组字段,其中<array>是数组字段的名称,$表示匹配到的第一个元素。
  • value:表示要更新的值。

使用这个语法可以将数组中匹配到的第一个元素更新为指定的值。请注意,这个语法只能用于更新数组中匹配到的第一个元素,无法用于更新数组中的所有元素。如果需要更新数组中的所有元素,可以使用<array>.$[]语法。

1. 更新数组中的值

构造测试数据:

db.students.drop()
db.students.insertMany( [{ "_id" : 1, "grades" : [ 85, 80, 80 ] },{ "_id" : 2, "grades" : [ 88, 90, 92 ] },{ "_id" : 3, "grades" : [ 85, 100, 90 ] }
] )

查询 students 集合中 _id=1 并且 grades 数组包含80 的文档,将 grades 数组中第一个值为80的元素更新为82,如果不知道该元素在数组中的位置,$操作符:

db.students.updateOne({ _id: 1, grades: 80 },{ $set: { "grades.$" : 82 } }
)db.students.find({_id: 1})

如果知道该元素在数组中的位置 ,就可以直接使用数组元素的索引:

db.students.updateOne({ _id: 1, grades: 80 },{ $set: { "grades.1" : 82 } }
)

查询结果:

{"_id": 1,"grades": [85,82,80]
}

SpringBoot整合mongoDB 实现以上查询操作:

@Data
@Document(collection = "students")
public class Student {@Idprivate int id;private List<Integer> grades;
}
@Test
public void updateUser(){// 构建查询条件Query query = new Query();query.addCriteria(Criteria.where("_id").is(1).and("grades").is(80));// 构建更新操作Update update = new Update();update.set("grades.$", 82);// 执行更新操作mongoTemplate.updateFirst(query, update, "students");
}

2. 更新数组中的嵌入文档

db.collection.updateOne({ <query selector> },{ <update operator>: { "array.$.field" : value } }
)

构造测试数据:

db.students.insertOne({_id: 4,course: [{ grade: 80, mean: 75, std: 8 },{ grade: 85, mean: 90, std: 5 },{ grade: 85, mean: 85, std: 8 }]}
)

查询 _id=4 且 course.grade 包含85的文档,将 course 数组中第一个 grade=85 的文档的 std 字段更新为6,如果不知道该元素在数组中的位置,就可以使用位置$操作符:

db.students.updateOne({ _id: 4, "course.grade": 85 },{ $set: { "course.$.std" : 6 } }
)db.students.find({_id: 4})

查询结果:

{"_id": 4,"course": [{"grade": 80,"mean": 75,"std": 8},{"grade": 85,"mean": 90,"std": 6},{"grade": 85,"mean": 85,"std": 8}]
}

如果知道该元素在数组中的位置 ,就可以直接使用数组元素的索引:

db.students.updateOne({ _id: 4, "course.grade": 85 },{ $set: { "course.1.std" : 6 } }
)

SpringBoot整合mongoDB 实现以上查询操作:

@Data
@Document(collection = "students")
public class Student {@Idprivate int id;private List<Integer> grades;private List<Grade> course;@Datapublic static class Grade {private int grade;private int mean;private int std;}
}
@Test
public void updateUser(){// 构建查询条件Query query = new Query();query.addCriteria(Criteria.where("_id").is(4).and("course.grade").is(85));// 构建更新操作Update update = new Update();update.set("course.$.std", 6);// 执行更新操作mongoTemplate.updateFirst(query, update, "students");
}

2. $[]

$[] 将数组中的所有元素都更新为指定的值。

db.collection.updateOne({ <query conditions> },{ <update operator>: { "<array>.$[]" : value } }
)

具体解释如下:

  • <update operator>:表示要使用的更新操作符,例如 s e t 、 set、 setinc、$push等。
  • <array>.$[]”:表示要更新的数组字段,其中<array>是数组字段的名称,$[]表示匹配数组中的所有元素。
  • value:表示要更新的值。

使用这个语法可以将数组中的所有元素都更新为指定的值。请注意,这个语法只能用于更新数组中的所有元素,无法用于更新数组中的部分元素。

1. 更新数组中的所有元素

构造测试数据:

db.students.insertMany( [{ "_id" : 1, "grades" : [ 85, 82, 80 ] },{ "_id" : 2, "grades" : [ 88, 90, 92 ] },{ "_id" : 3, "grades" : [ 85, 100, 90 ] }
] )

查询 students 集合中的所有文档,将 grades 数组中的所有元素都增加10,其中$[]表示匹配数组中的所有元素:

db.students.updateMany({ },{ $inc: { "grades.$[]": 10 } },
)db.students.find()

查询结果:

// 1
{"_id": 1,"grades": [95,92,90]
}// 2
{"_id": 2,"grades": [98,100,102]
}// 3
{"_id": 3,"grades": [95,110,100]
}

SpringBoot 整合 mongoDB 实现以上查询操作:

@Data
@Document(collection = "students")
public class Student {@Idprivate int id;private List<Integer> grades;
}
@Test
public void updateUser(){// 构建查询条件Query query = new Query();// 构建更新操作Update update = new Update();update.inc("grades.$[]", 10);// 执行更新操作mongoTemplate.updateMulti(query, update, "students");
}

2. 更新数组中的所有嵌入文档

db.collection.updateOne({ <query selector> },{ <update operator>: { "array.$[].field" : value } }
)

构造测试数据:

db.students.insertMany( [{"_id" : 1,"course" : [{ "grade" : 80, "mean" : 75, "std" : 8 },{ "grade" : 85, "mean" : 90, "std" : 6 },{ "grade" : 85, "mean" : 85, "std" : 8 }]},{"_id" : 2,"course" : [{ "grade" : 90, "mean" : 75, "std" : 8 },{ "grade" : 87, "mean" : 90, "std" : 5 },{ "grade" : 85, "mean" : 85, "std" : 6 }]}
] )

查询 students 集合中的所有文档,将 course 数组中的所有元素的std字段都增加10,其中$[]表示匹配数组中的所有元素:

db.students.updateMany({ },{ $inc: { "course.$[].std" : -2 } },
)db.students.find()

查询结果:

// 1
{"_id": 1,"course": [{"grade": 80,"mean": 75,"std": 18},{"grade": 85,"mean": 90,"std": 16},{"grade": 85,"mean": 85,"std": 18}]
}// 2
{"_id": 2,"course": [{"grade": 90,"mean": 75,"std": 18},{"grade": 87,"mean": 90,"std": 15},{"grade": 85,"mean": 85,"std": 16}]
}

SpringBoot 整合 MongoDB 实现以上查询操作:

@Data
@Document(collection = "students")
public class Student {@Idprivate int id;private List<Integer> grades;private List<Grade> course;@Datapublic static class Grade {private int grade;private int mean;private int std;}
}
@SpringBootTest
@RunWith(SpringRunner.class)
public class BeanLoadServiceTest {@Autowiredprivate MongoTemplate mongoTemplate;@Testpublic void updateUser(){// 构建查询条件Query query = new Query();// 构建更新操作Update update = new Update();update.inc("course.$[].std", 10);// 执行更新操作mongoTemplate.updateMulti(query, update, "students");}
}

3. $pop

$pop 从数组字段中删除第一个或最后一个元素。

db.collection.updateOne(<query>, { $pop: { <field>: <-1 | 1>, ... } }
)

<field>是要操作的数组字段,<-1 | 1>表示删除的方向,-1表示删除第一个元素,1表示删除最后一个元素。

1. 删除数组的第一个元素

构造测试数据:

db.students.insertOne( { _id: 1, grades: [ 8, 9, 10 ] } )

查询 students 集合中 _id=1 的文档,将 grades 数组中的第一个元素删除:

db.students.updateOne({ _id: 1 }, { $pop: { grades: -1 } } 
)db.students.find({_id:1})

查询结果:

{"_id": 1,"grades": [9,10]
}

SpringBoot 整合 MongoDB 实现以上查询操作:

@Data
@Document(collection = "students")
public class Student {@Idprivate int id;private List<Integer> grades;
}
@Test
public void updateUser(){// 构建查询条件Query query = new Query(Criteria.where("_id").is(1));// 构建更新操作Update update = new Update();update.pop("grades",Update.Position.FIRST);// 执行更新操作mongoTemplate.updateMulti(query, update, "students");
}

2. 删除数组的最后一个元素

db.students.updateOne({ _id: 1 }, { $pop: { grades: 1 } } 
)db.students.find({_id:1})

查询结果:

{"_id": 1,"grades": [ 9 ]
}

SpringBoot 整合 MongoDB 实现以上查询操作:

@Data
@Document(collection = "students")
public class Student {@Idprivate int id;private List<Integer> grades;
}
@Test
public void updateUser(){// 构建查询条件Query query = new Query(Criteria.where("_id").is(1));// 构建更新操作Update update = new Update();update.pop("grades",Update.Position.LAST);// 执行更新操作mongoTemplate.updateMulti(query, update, "students");
}

4. $pull

$pull 是 MongoDB 的更新操作符,用于从数组字段中删除匹配的元素。

db.collection.updateOne(<query>, { $pull: { <field1>: <value|condition>, <field2>: <value|condition>, ... } }
)

从数组字段中删除匹配的元素。以下是该语法的解释:

  • <field1>, <field2>, ... 是要进行更新的字段名。
  • <value|condition> 是要从数组字段中删除的元素值或删除的条件。

1. 删除所有等于指定值的项

构造测试数据:

db.stores.insertMany( [{_id: 1,fruits: [ "apples", "pears", "oranges", "grapes", "bananas" ],vegetables: [ "carrots", "celery", "squash", "carrots" ]},{_id: 2,fruits: [ "plums", "kiwis", "oranges", "bananas", "apples" ],vegetables: [ "broccoli", "zucchini", "carrots", "onions" ]}
] )

① 删除 stores 集合中vegetables 数组中的 "carrots":

db.stores.updateMany({ },{ $pull: { vegetables: "carrots" } }
)db.stores.find()

查询结果:

// 1
{"_id": 1,"fruits": ["apples","pears","oranges","grapes","bananas"],"vegetables": ["celery","squash"]
}// 2
{"_id": 2,"fruits": ["plums","kiwis","oranges","bananas","apples"],"vegetables": ["broccoli","zucchini","onions"]
}

SpringBoot 整合 MongoDB 实现以上查询操作:

@Data
@Document(collection = "stores")
public class Store {@Idprivate int id;private List<String> fruits;private List<String> vegetables;
}
@Test
public void updateStore(){// 构建查询条件Query query = new Query();// 构建更新操作Update update = new Update();update.pull("vegetables","carrots");// 执行更新操作mongoTemplate.updateMulti(query, update, "stores");
}

② 删除 stores 集合中 fruits 数组中的 "apples""oranges"

db.stores.updateMany({ },{ $pull: { fruits: { $in: [ "apples", "oranges" ] } } }
)

查询结果:

// 1
{"_id": 1,"fruits": ["pears","grapes","bananas"],"vegetables": ["carrots","celery","squash","carrots"]
}// 2
{"_id": 2,"fruits": ["plums","kiwis","bananas"],"vegetables": ["broccoli","zucchini","carrots","onions"]
}

SpringBoot 整合 MongoDB 实现以上查询操作:

@Data
@Document(collection = "stores")
public class Store {@Idprivate int id;private List<String> fruits;private List<String> vegetables;
}
@Test
public void updateStore(){// 构建查询条件Query query = new Query();// 构建更新操作String[] values = new String[]{ "apples", "oranges"};Update update = new Update();update.pullAll("fruits", values);// 执行更新操作mongoTemplate.updateMulti(query, update, "stores");
}

③ 删除 stores 集合中fruits 数组中的 "apples""oranges"vegetables 数组中的 "carrots"

db.stores.updateMany({ },{ $pull: { fruits: { $in: [ "apples", "oranges" ] }, vegetables: "carrots" } }
)

查询结果:

// 1
{"_id": 1,"fruits": ["pears","grapes","bananas"],"vegetables": ["celery","squash"]
}// 2
{"_id": 2,"fruits": ["plums","kiwis","bananas"],"vegetables": ["broccoli","zucchini","onions"]
}

SpringBoot 整合 MongoDB 实现以上查询操作:

@Data
@Document(collection = "stores")
public class Store {@Idprivate int id;private List<String> fruits;private List<String> vegetables;
}
@Test
public void updateStore(){// 构建查询条件Query query = new Query();// 构建更新操作String[] values = new String[]{ "apples", "oranges"};Update update = new Update();update.pull("vegetables","carrots");update.pullAll("fruits", values);// 执行更新操作mongoTemplate.updateMulti(query, update, "stores");
}

2. 删除与指定条件匹配的所有项

构造测试数据:

db.students.insertMany( [{ "_id" : 1, "grades" : [ 85, 80, 80 ] },{ "_id" : 2, "grades" : [ 88, 90, 92 ] },{ "_id" : 3, "grades" : [ 85, 100, 90 ] }
] )

查询 _id=1的文档,将 grades 数组中大于80 的所有项删除 :

db.students.updateOne( { _id: 1 }, { $pull: { grades: { $gt: 80 } } } )
db.students.find()

查询结果:

// 1
{"_id": 1,"grades": [80,80]
}// 2
{"_id": 2,"grades": [88,90,92]
}// 3
{"_id": 3,"grades": [85,100,90]
}

SpringBoot 整合 MongoDB 实现以上查询操作:

@Data
@Document(collection = "students")
public class Student {@Idprivate int id;private List<Integer> grades;
}
@Test
public void updateUser(){// 构建查询条件Query query = new Query(Criteria.where("_id").is(1));// 构建更新操作Update update = new Update();update.pull("grades", Query.query(Criteria.where("grades").gt(80)));// 执行更新操作mongoTemplate.updateMulti(query, update, "students");
}

3. 从文档数组中删除项

构造测试数据:

db.survey.insertMany([{_id: 1,results: [{ item: "A", score: 5 },{ item: "B", score: 8 }]},{_id: 2,results: [{ item: "C", score: 8 },{ item: "B", score: 4 }]}
] )

删除 results 数组中 score=8 并且 item=“B” 的文档:

db.survey.updateMany({ },{ $pull: { results: { score: 8 , item: "B" } } }
)db.survey.find()

查询结果:

// 1
{"_id": 1,"results": [{"item": "A","score": 5}]
}// 2
{"_id": 2,"results": [{"item": "C","score": 8},{"item": "B","score": 4}]
}

SpringBoot 整合 MongoDB 实现以上查询操作:

@Data
@Document(collection = "survey")
public class Survey {@Idprivate int id;private List<Result> results;@Datapublic class Result {private String item;private int score;}
}
@Test
public void updateResult(){// 构建查询条件Query query = new Query();// 构建更新操作Update update = new Update();update.pull("results", Query.query(Criteria.where("score").is(8).and("item").is("B")));// 执行更新操作mongoTemplate.updateMulti(query, update, "survey");
}

4. 从嵌套数组中删除文档

构造测试数据:

db.survey.drop()db.survey.insertMany( [{_id: 1,results: [{item: "A",score: 5,answers: [ { q: 1, a: 4 }, { q: 2, a: 6 } ]},{item: "B",score: 8,answers: [ { q: 1, a: 8 }, { q: 2, a: 9 } ]}]},{_id: 2,results: [{item: "C",score: 8,answers: [ { q: 1, a: 8 }, { q: 2, a: 7 } ]},{item: "B",score: 4,answers: [ { q: 1, a: 0 }, { q: 2, a: 8 } ]}]}
] )

删除 results 数组中的 answers 数组中 q=2 并且 a>=8 的文档:

db.survey.updateMany({ },{$pull:{results:{answers: { $elemMatch: { q: 2, a: { $gte: 8 } } }}}}
)db.survey.find()

查询结果:

// 1
{"_id": 1,"results": [{"item": "A","score": 5,"answers": [{"q": 1,"a": 4},{"q": 2,"a": 6}]}]
}// 2
{"_id": 2,"results": [{"item": "C","score": 8,"answers": [{"q": 1,"a": 8},{"q": 2,"a": 7}]}]
}

SpringBoot 整合 MongoDB 实现以上查询操作:

@Data
@Document(collection = "survey")
public class Survey {@Idprivate int id;private List<Result> results;@Datapublic class Result {private String item;private int score;private List<Answer> answers;}@Datapublic class Answer {private int q;private int a;}
}
@Test
public void updateResult(){// 构建查询条件Query query = new Query();// 构建更新操作Update update = new Update();update.pull("results", Query.query(Criteria.where("answers").elemMatch(Criteria.where("q").is(2).and("a").gte(8))));// 执行更新操作mongoTemplate.updateMulti(query, update, "survey");
}

5. $push

$push 支持一次向多个数组字段添加元素的功能:

{ $push: { <field1>: <value1>, <field2>: <value2>, ... } }

其中,<field1>、<field2>等是要更新的数组字段,<value1>、<value2>等是要添加到对应数组中的元素。

您可以使用 $push 操作符与以下修饰符一起使用:

修饰符说明
$each向数组字段追加多个值。
$slice限制数组元素的数量。
$sort对数组元素进行排序。
$position指定数组中插入新元素的位置。如果没有 $position 修饰符,$push 会将元素追加到数组的末尾。

1. $push 将值追加到数组

构造测试数据:

db.students.insertOne( { _id: 1, grades: [ 44, 78, 38, 80 ] } )

向 _id=1 文档的 grades 数组中追加一个元素 89:

db.students.updateOne({ _id: 1 },{ $push: { grades: 89 } }
)db.students.findOne()

查询结果:

// 1
{"_id": 1,"grades": [44,78,38,80,89]
}

SpringBoot 整合 MongoDB 实现以上查询操作:

@Data
@Document(collection = "students")
public class Student {@Idprivate int id;private List<Integer> grades;
}
@Test
public void updateStudent(){// 构建查询条件Query query = new Query();query.addCriteria(Criteria.where("_id").is(1));// 构建更新操作Update update = new Update();update.push("grades",89);// 执行更新操作mongoTemplate.updateMulti(query, update, "students");
}

构造测试数据:

db.students.drop()db.students.insertOne( { _id: 1, grades: [ 44, 78, 38, 80 ] } )db.students.insertMany( [{ _id: 2, grades: [ 45, 78, 38, 80, 89 ] } ,{ _id: 3, grades: [ 46, 78, 38, 80, 89 ] } ,{ _id: 4, grades: [ 47, 78, 38, 80, 89 ] }
] )

向每个文档的 scores 数组追加一个元素 95:

db.students.updateMany({ },{ $push: { grades: 95 } }
)db.students.find();

查询结果:

[{ _id: 1, grades: [ 44, 78, 38, 80, 89, 95 ] },{ _id: 2, grades: [ 45, 78, 38, 80, 89, 95 ] },{ _id: 3, grades: [ 46, 78, 38, 80, 89, 95 ] },{ _id: 4, grades: [ 47, 78, 38, 80, 89, 95 ] }
]

SpringBoot 整合 MongoDB 实现以上查询操作:

@Data
@Document(collection = "students")
public class Student {@Idprivate int id;private List<Integer> grades;
}
@Test
public void updateStudent(){// 构建查询条件Query query = new Query();// 构建更新操作Update update = new Update();update.push("grades",89);// 执行更新操作mongoTemplate.updateMulti(query, update, "students");
}

2. $push 与 $each

使用 $push$each 修饰符将多个值附加到数组字段。

向 _id=1 文档的 grades 数组中追加多个值 [ 90, 92, 85 ]:

db.students.drop()db.students.insertMany( [{ "_id" : 1, "grades" : [ 85, 80, 80 ] },{ "_id" : 2, "grades" : [ 88, 90, 92 ] },{ "_id" : 3, "grades" : [ 85, 100, 90 ] }
] )db.students.updateOne({ _id: 1 },{ $push: { grades: { $each: [ 90, 92, 85 ] } } }
)db.students.find({_id:1})

查询结果:

{ _id: 1, grades: [ 44, 78, 38, 80, 89, 95, 90, 92, 85 ] }

SpringBoot整合MongoDB实现:

@Data
@Document(collection = "students")
public class Student {@Idprivate int id;private List<Integer> grades;
}
@Test
public void updateResult(){// 构建查询条件Query query = new Query(Criteria.where("_id").is(1));// 构建更新操作Update update = new Update();update.push("grades").each(90,92,95);// 执行更新操作mongoTemplate.updateMulti(query, update, "students");
}

3. $push 与 $each 与 $positon

使用 $each,可以将一个包含多个元素的数组添加到目标数组字段中,使用 $positon 可以指定插入元素的数组位置。

{$push: {<arrayField>: {$each: [ <value1>, <value2>, ... ],$position: <num>}}
}

构造测试数据:

db.students.drop()db.students.insertMany( [{ "_id" : 1, "grades" : [ 85, 80, 80 ] },{ "_id" : 2, "grades" : [ 88, 90, 92 ] },{ "_id" : 3, "grades" : [ 85, 100, 90 ] }
] )

向 grades 数组索引为1的位置添加 50,60,70 三个值:

db.students.updateOne({ _id: 1 },{$push: {grades: {$each: [ 50, 60, 70 ],$position: 1}}}
)db.students.find({_id:1})

查询结果:

// 1
{"_id": 1,"grades": [85,50,60,70,80,80]
}

SpringBoot 整合 MongoDB 实现:

@Data
@Document(collection = "students")
public class Student {@Idprivate int id;private List<Integer> grades;
}
@Test
public void updateResult(){// 构建查询条件Query query = new Query(Criteria.where("_id").is(5));// 构建更新操作Update update = new Update().push("grades").atPosition(1).each(50,60,70);// 执行更新操作mongoTemplate.updateMulti(query, update, "students");
}

4. $slice

$slice 用于在查询结果中限制数组字段的元素数量,如果num为正数则从前往后数,如果num为负数则从后往前数。

{ arrayField: {  $slice: <num>} }

构造测试数据:

db.students.drop()db.students.insertMany( [{ "_id" : 1, "grades" : [ 85, 80, 80 ] },{ "_id" : 2, "grades" : [ 88, 90, 92 ] },{ "_id" : 3, "grades" : [ 85, 100, 90 ] }
] )

查询 grades 数组中的前2个元素:

db.students.find({ _id: 1 },{ grades: { $slice: 2 } }
)

查询结果:

{ "_id" : 1, "grades" : [ 85, 80] }

查询 scores 数组中的后2个元素:

db.students.find({ _id: 1 },{ scores: { $slice: -2 } }
)

查询结果:

{ "_id" : 1, "grades" : [ 80, 80] }

5. $push 与 $slice

{$push: {<arrayField>: {$each: [ <value1>, <value2>, ... ],$slice: <num>}}
}

构造测试数据:

db.students.drop()db.students.insertMany( [{ "_id" : 1, "grades" : [ 85, 80, 80 ] },{ "_id" : 2, "grades" : [ 88, 90, 92 ] },{ "_id" : 3, "grades" : [ 85, 100, 90 ] }
] )

向 grades数组索引为 0 的位置添加10,20,30三个元素,并返回数组的前2个元素:

db.students.updateOne({ _id: 1 },{$push: {grades: {$each: [ 10, 20, 30 ],$position: 0,$slice: 2}}}
)db.students.find({_id:1})

查询结果:

{"_id": 1,"grades": [10,20]
}

SpringBoot 整合 MongoDB 实现:

@Data
@Document(collection = "students")
public class Student {@Idprivate int id;private List<Integer> grades;
}
@Test
public void updateResult(){// 构建查询条件Query query = new Query(Criteria.where("_id").is(5));// 构建更新操作Update update = new Update().push("grades").atPosition(1).each(50,60,70);// 执行更新操作mongoTemplate.updateMulti(query, update, "students");
}

6. $push 与 $sort

$sort 修饰符在 $push 操作期间对数组的元素进行排序。要使用 $sort 修饰符,它必须与 $each 修饰符同时出现:

{$push: {<field>: {$each: [ <value1>, <value2>, ... ],$sort: <sort specification>}}
}

构造测试数据:

db.students.drop()db.students.insertOne({"_id": 1,"quizzes": [{ "id" : 1, "score" : 6 },{ "id" : 2, "score" : 9 }]}
)

以下更新将其他文档附加到 quizzes 数组,按 score 字段对数组的所有元素进行升序排序:

db.students.updateOne({ _id: 1 },{$push: {quizzes: {$each: [ { id: 3, score: 8 }, { id: 4, score: 7 }, { id: 5, score: 6 } ],$sort: { score: 1 }}}}
)db.students.find()

查询结果:

// 1
{"_id": 1,"quizzes": [{"id": 1,"score": 6},{"id": 5,"score": 6},{"id": 4,"score": 7},{"id": 3,"score": 8},{"id": 2,"score": 9}]
}

SpringBoot 整合 MongoDB:

@Data
@Document(collection = "students")
public class Student {@Idprivate int id;@AllArgsConstructor@NoArgsConstructor@Datapublic static class Quiz {private int wk;private int score;}
}
@Test
public void updateResult(){// 构建查询条件Query query = new Query(Criteria.where("_id").is(1));// 构建更新操作Update update = new Update().push("quizzes").sort(Sort.by(Sort.Direction.ASC, "score")).each(new Student.Quiz(3,8),new Student.Quiz(4,7),new Student.Quiz(5,6));// 执行更新操作mongoTemplate.updateMulti(query, update, "students");
}

构造测试数据 :

db.students.drop()db.students.insertMany( [{ "_id" : 1, "grades" : [ 85, 80, 80 ] },{ "_id" : 2, "grades" : [ 88, 90, 92 ] },{ "_id" : 3, "grades" : [ 85, 100, 90 ] }
] )

向grades数组中添加元素40,60,按 score 字段对数组的所有元素进行升序排序:

db.students.updateOne({ _id: 2 },{ $push: { grades: { $each: [ 40, 60 ], $sort: 1 } } }
)db.students.find()

查询结果:

// 1
{"_id": 1,"grades": [85,80,80]
}// 2
{"_id": 2,"grades": [40,60,88,90,92]
}// 3
{"_id": 3,"grades": [85,100,90]
}

SpringBoot 整合 MongoDB:

@Data
@Document(collection = "students")
public class Student {@Idprivate int id;private List<Integer> grades;
}
@Test
public void updateResult(){// 构建查询条件Query query = new Query(Criteria.where("_id").is(2));// 构建更新操作Update update = new Update().push("grades").sort(Sort.Direction.ASC).each(40,60);// 执行更新操作mongoTemplate.updateMulti(query, update, "students");
}

7. $push 与 $each 与 $position 与 $sort 与 $slice

构造测试数据:

db.students.drop()db.students.insertOne({"_id" : 5,"quizzes" : [{ "wk": 1, "score" : 10 },{ "wk": 2, "score" : 8 },{ "wk": 3, "score" : 5 },{ "wk": 4, "score" : 6 }]}
)

以下 $push 操作使用:

  • $each 修饰符,将多个文档添加到 quizzes 数组。
  • $position修饰符,将多个文档添加到 quizzes 数组索引为0的位置。
  • $sort 修改符,对 quizzes 数组按照 score 字段降序排序。
  • $slice 修饰符,仅保留 quizzes 数组中的前3个元素。
db.students.updateOne({ _id: 5 },{$push: {quizzes: {$each: [ { wk: 5, score: 8 }, { wk: 6, score: 7 }, { wk: 7, score: 6 } ],$position: 0,$sort: { score: -1 },$slice: 3}}}
)db.students.find({_id:5})

查询结果:

{"_id" : 5,"quizzes" : [{ "wk" : 1, "score" : 10 },{ "wk" : 5, "score" : 8 },{ "wk" : 2, "score" : 8 }]
}

SpringBoot整合MongoDB实现:

public class Student {@Idprivate int id;private List<Integer> grades;private List<Quiz> quizzes;@AllArgsConstructor@NoArgsConstructor@Datapublic static class Quiz {private int wk;private int score;}
}
@Test
public void updateResult(){// 构建查询条件Query query = new Query(Criteria.where("_id").is(5));// 构建更新操作Update update = new Update().push("quizzes").atPosition(0).slice(3).sort(Sort.by(Sort.Direction.DESC, "score")).each(new Student.Quiz(5,8), new Student.Quiz(6,7), new Student.Quiz(7,6));// 执行更新操作mongoTemplate.updateMulti(query, update, "students");
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com