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): 登录、购…...
内存分配函数malloc kmalloc vmalloc
内存分配函数malloc kmalloc vmalloc malloc实现步骤: 1)请求大小调整:首先,malloc 需要调整用户请求的大小,以适应内部数据结构(例如,可能需要存储额外的元数据)。通常,这包括对齐调整,确保分配的内存地址满足特定硬件要求(如对齐到8字节或16字节边界)。 2)空闲…...
地震勘探——干扰波识别、井中地震时距曲线特点
目录 干扰波识别反射波地震勘探的干扰波 井中地震时距曲线特点 干扰波识别 有效波:可以用来解决所提出的地质任务的波;干扰波:所有妨碍辨认、追踪有效波的其他波。 地震勘探中,有效波和干扰波是相对的。例如,在反射波…...
《用户共鸣指数(E)驱动品牌大模型种草:如何抢占大模型搜索结果情感高地》
在注意力分散、内容高度同质化的时代,情感连接已成为品牌破圈的关键通道。我们在服务大量品牌客户的过程中发现,消费者对内容的“有感”程度,正日益成为影响品牌传播效率与转化率的核心变量。在生成式AI驱动的内容生成与推荐环境中࿰…...
【Oracle】分区表
个人主页:Guiat 归属专栏:Oracle 文章目录 1. 分区表基础概述1.1 分区表的概念与优势1.2 分区类型概览1.3 分区表的工作原理 2. 范围分区 (RANGE Partitioning)2.1 基础范围分区2.1.1 按日期范围分区2.1.2 按数值范围分区 2.2 间隔分区 (INTERVAL Partit…...
【7色560页】职场可视化逻辑图高级数据分析PPT模版
7种色调职场工作汇报PPT,橙蓝、黑红、红蓝、蓝橙灰、浅蓝、浅绿、深蓝七种色调模版 【7色560页】职场可视化逻辑图高级数据分析PPT模版:职场可视化逻辑图分析PPT模版https://pan.quark.cn/s/78aeabbd92d1...
初探Service服务发现机制
1.Service简介 Service是将运行在一组Pod上的应用程序发布为网络服务的抽象方法。 主要功能:服务发现和负载均衡。 Service类型的包括ClusterIP类型、NodePort类型、LoadBalancer类型、ExternalName类型 2.Endpoints简介 Endpoints是一种Kubernetes资源…...
JS设计模式(4):观察者模式
JS设计模式(4):观察者模式 一、引入 在开发中,我们经常会遇到这样的场景:一个对象的状态变化需要自动通知其他对象,比如: 电商平台中,商品库存变化时需要通知所有订阅该商品的用户;新闻网站中࿰…...
保姆级教程:在无网络无显卡的Windows电脑的vscode本地部署deepseek
文章目录 1 前言2 部署流程2.1 准备工作2.2 Ollama2.2.1 使用有网络的电脑下载Ollama2.2.2 安装Ollama(有网络的电脑)2.2.3 安装Ollama(无网络的电脑)2.2.4 安装验证2.2.5 修改大模型安装位置2.2.6 下载Deepseek模型 2.3 将deepse…...
springboot整合VUE之在线教育管理系统简介
可以学习到的技能 学会常用技术栈的使用 独立开发项目 学会前端的开发流程 学会后端的开发流程 学会数据库的设计 学会前后端接口调用方式 学会多模块之间的关联 学会数据的处理 适用人群 在校学生,小白用户,想学习知识的 有点基础,想要通过项…...
JS手写代码篇----使用Promise封装AJAX请求
15、使用Promise封装AJAX请求 promise就有reject和resolve了,就不必写成功和失败的回调函数了 const BASEURL ./手写ajax/test.jsonfunction promiseAjax() {return new Promise((resolve, reject) > {const xhr new XMLHttpRequest();xhr.open("get&quo…...
