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、 set、inc、$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、 set、inc、$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");
}
相关文章:

MongoDB - 数组更新操作符:$、$[]、$pop、$pull、$push、$each、$sort、$slice、$position
文章目录 1. $1. 更新数组中的值2. 更新数组中的嵌入文档 2. $[]1. 更新数组中的所有元素2. 更新数组中的所有嵌入文档 3. $pop1. 删除数组的第一个元素2. 删除数组的最后一个元素 4. $pull1. 删除所有等于指定值的项2. 删除与指定条件匹配的所有项3. 从文档数组中删除项4. 从嵌…...

多GPU并行处理[任务分配、进程调度、资源管理、负载均衡]
1. 多GPU并行处理设计 设计思路: 实现基于多GPU的并行任务处理,每个GPU运行独立的任务,以加速整体的处理速度。 实现机制: 进程隔离: 利用multiprocessing.Process为每个GPU创建独立的工作进程。 GPU资源限制: 通过设置CUDA_VISIBLE_DEVICES环境变量&…...

项目部署到服务器
(相关资源都给出来了) 1 下载MobaXterm,然后打开 正常连接输入你的服务器IP,用户名可以起名为root 2 将JDK,Tomcat,mysql安装包 布置到服务器中(JDK官网地址:https://www.oracle.com/java/technologies/downloads/#java8 mysql官网地址: …...

Idea2024 创建Meaven项目没有src文件夹
1、直接创建 新建maven项目,发现没有src/main/java 直接新建文件夹:右击项目名->new->Directory 可以看到idea给出了快捷创建文件夹的选项,可以根据需要创建,这里点击src/main/java 回车,可以看到文件夹已经创建…...

LeetCode 2766.重新放置石块:哈希表
【LetMeFly】2766.重新放置石块:哈希表 力扣题目链接:https://leetcode.cn/problems/relocate-marbles/ 给你一个下标从 0 开始的整数数组 nums ,表示一些石块的初始位置。再给你两个长度 相等 下标从 0 开始的整数数组 moveFrom 和 moveTo…...

基于STM32的农业大棚温湿度采集控制系统的设计
目录 1、设计要求 2、系统功能 3、演示视频和实物 4、系统设计框图 5、软件设计流程图 6、原理图 7、主程序 8、总结 🤞大家好,这里是5132单片机毕设设计项目分享,今天给大家分享的是智能教室。 设备的详细功能见网盘中的文章《8、基…...

go语言的命名规则
身为前端为什么去学go语言呢?我认为go在未来可能会给我带来一些收益。自认为收益是去做一件事情不可缺少的因素,就好像是你努力之后得到回报,努力的欲望会越来越强。《Head First Go》这本书里作者有一句话,如果你已经掌握了一门编…...

新增ClamAV病毒扫描功能、支持Java和Go运行环境,1Panel开源面板v1.10.12版本发布
2024年7月19日,现代化、开源的Linux服务器运维管理面板1Panel正式发布了v1.10.12版本。 在这一版本中,1Panel新增了多项实用功能。社区版方面,1Panel新增ClamAV病毒扫描功能、支持Java和Go运行环境,同时1Panel还新增了文件编辑器…...

Windows通过命令查看mac : getmac
要查看本机网卡mac,可以通过ipconfig /all 显示,但输出内容过多 可以通过getmac命令查看 示例 C:\Users\Desktop> getmac物理地址 传输名称暂缺 没有硬件 1C-1B-B5-04-E2-7D \Device\Tcpip_{80096E40-D51D-490C-9AF7-…...

Android笔试面试题AI答之Android系统与综合类(1)
答案仅供参考,来着文心一言、Kimi.ai 目录 1.简述嵌入式实时操作系统,Android 操作系统属于实时操作系统吗?嵌入式实时操作系统简述Android操作系统是否属于实时操作系统 2.简述Android系统的优势和不足?3.简述Android的系统架构 ࿱…...

【Android】数据存储方案——文件存储、SharedPreferences、SQLite数据库用法总结
文章目录 文件存储存储到文件读取文件 SharedPreferences存储存储获取SharedPreferences对象Context 类的 getSharedPreferences() 方法Activity 类的 getPreferences() 方法PreferenceManager 类中的 getDefaultSharedPreferences() 方法 示例 读取记住密码的功能 SQLite数据库…...

抖音矩阵管理系统功能说明:一站式掌握
在当下这个信息爆炸的时代,抖音作为短视频领域的佼佼者,其用户规模持续扩大,影响力日益增强。对于内容创作者和营销人员来说,如何高效管理抖音账号,实现内容的多平台分发和精准触达,成为了亟待解决的问题。…...

旅游卡使用指南及常见疑问解答
近期,许多朋友对旅游卡的免费旅游政策表示浓厚兴趣,但心中不免存疑:这真的是全程免费,无需自费一分吗? 在此,我们明确告知:免费旅游确实存在,但享受范围与条件需清晰界定。 本文将…...

【MySQL篇】Percona XtraBackup标准化全库完整备份策略(第三篇,总共五篇)
💫《博主介绍》:✨又是一天没白过,我是奈斯,DBA一名✨ 💫《擅长领域》:✌️擅长Oracle、MySQL、SQLserver、阿里云AnalyticDB for MySQL(分布式数据仓库)、Linux,也在扩展大数据方向的知识面✌️…...

背单词工具(C++)
功能分析 生词本管理: 创建生词本文件:在构造函数中创建了“生词本.txt”“背词历史.log”“历史记录.txt”三个文件。添加单词:用户可以输入单词、词性和解释,将其添加到生词本中。查询所有单词:展示生词本中所有的单…...

面试八股 | 数据库引擎 | InnoDB和myISAM的区别?
⭐️⭐️⭐️InnoDB和MyISAM的区别? InnoDB : 1、使用的是行锁,操作时候只锁一行数据,不会对其他有影响,适合高并发工作 2、支持事务 3、不仅缓存索引还要缓存真实数据,适合高并发 4、默认安装 5、支持外键 6、…...

GEE计算五种植被指数(NDVI、EVI2、RVI、MTVI2、OSAVI)
目录 计算公式源代码计算公式 源代码 // 定义感兴趣区域(这里以一个简单的矩形区域为例) var region = ee.FeatureCollection("projects/a-flyllf0313/assets/dachang"); // 定义时间范围 var startDate = 2023-04-18; var endDate &...

C/S架构和B/C架构
C/S架构(Client/Server Architecture)和B/C架构(Browser/Client Architecture)是两种不同 的软件架构模型,它们各自有不同的特点和应用场景。 一、C/S架构(Client/Server Architecture) 1. 定…...

音乐曲谱软件Guitar Pro 8.2 for Mac 中文破解版
Guitar Pro 8.2 for Mac 中文破解版是一款功能强大的音乐曲谱软件,非常适合学习如何玩,改进技巧,重现喜爱的歌曲或陪伴自己。 Guitar Pro for Mac 是一款功能强大的音乐曲谱软件,非常适合学习如何玩,改进技巧…...

浅聊Web Storage(localStorage 和 sessionStorage)、cookie的使用场合
Web Storage(localStorage 和 sessionStorage)、cookie 一、Cookie二、Web StoragelocalStoragesessionStorage与 Cookies 的比较 一、Cookie Cookies 主要用于以下几种情况: 会话管理(Session Management): 登录、购…...

C语言输入输出缓冲机制
文章目录 输入输出缓冲机制概述为什么要有缓冲区缓冲区的类型引发缓冲区的刷新 原理实现 输入输出缓冲机制 概述 缓冲区又称为缓存,它是内存空间的一部分。也就是说,在内存空间中预留了一定的存储空间,这些存储空间用来缓冲输入 或者输出的数…...

javaEE-03-cookie与session
文章目录 Cookie创建Cookie获取Cookie更新CookieCookie 生命控制Cookie 有效路径 Session 会话创建和获取sessionSession 域数据的存取Session 生命周期控制浏览器和 Session 之间关联 Cookie Cookie 是服务器通知客户端保存键值对的一种技术,客户端有了 Cookie 后,…...

EtherNet/IP转Profinet协议网关(经典配置案例)
怎么样才能把EtherNet/IP和Profinet网络连接起来呢?这几天有几个朋友问到了这个问题,作者在这里统一为大家详细说明一下。其实有一个设备可以很轻松地解决这个问题,名为JM-PN-EIP,下面是详细介绍。 一,设备主要功能 1、捷米特J…...

华为云依赖引入错误
问题:记录一次项目加在华为云依赖错误,如下: 错误信息:Could not find artifact com.huawei.storage:esdk-obs-java:pom:3.1.2.1 in bintray-qcloud-maven-repo (https://dl.bintray.com/qcloud/maven-repo/) 找到本地仓库&#…...

【Ubuntu】Ubuntu 配置镜像源(ARM)
【Ubuntu】Ubuntu 配置镜像源(ARM) 零、起因 最近在QEMU中安装了个ubuntu-24.04-live-server-arm64,默认是国外的软件源,很慢,故替换到国内。 壹、替换 源地址(清华源) https://mirror.tun…...

速腾聚创激光雷达复现FAST-LIO
目录 1.软件环境 2.测试执行 3.代码学习 3.1.找主节点代码文件 3.2.整体流程结构 3.3.具体函数理解 记录复现FAST-LIO算法的过程和,代码梳理和理解 1.软件环境 Windows 10(64bits) VMware 16 Pro Ubuntu 20.04 ROS Noetic FAST-LIO的简化版、注释版。感谢…...

k8s核心知识总结
写在前面 时间一下子到了7月份尾;整个7月份都乱糟糟的,不管怎么样,日子还是得过啊, 1、7月份核心了解个关于k8s,iceberg等相关技术,了解了相关的基础逻辑,虽然和数开主线有点偏,但是…...

语言模型及数据集
一、定义 1、语言模型的目标是估计序列的联合概率,一个理想的语言模型就能够基于模型本身生成自然文本。 2、对一个文档(词元)序列进行建模, 假设在单词级别对文本数据进行词元化。 3、计数建模 (1)其中…...

linux如何卸载python3.5
卸载: 1、卸载python3.5 sudo apt-get remove python3.5 2、卸载python3.5及其依赖 sudo apt-get remove --auto-remove python3.5 3、清除python3.5 sudo apt-get purge python3.5 或者 sudo apt-get purge --auto-remove python3.5...

【BUG】已解决:TypeError: expected string or bytes-like object
TypeError: expected string or bytes-like object 目录 TypeError: expected string or bytes-like object 【常见模块错误】 【解决方案】 常见原因及解决方法 示例代码 欢迎来到英杰社区https://bbs.csdn.net/topics/617804998 欢迎来到我的主页,我是博主英杰…...