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): 登录、购…...
Spring Boot 实现流式响应(兼容 2.7.x)
在实际开发中,我们可能会遇到一些流式数据处理的场景,比如接收来自上游接口的 Server-Sent Events(SSE) 或 流式 JSON 内容,并将其原样中转给前端页面或客户端。这种情况下,传统的 RestTemplate 缓存机制会…...
循环冗余码校验CRC码 算法步骤+详细实例计算
通信过程:(白话解释) 我们将原始待发送的消息称为 M M M,依据发送接收消息双方约定的生成多项式 G ( x ) G(x) G(x)(意思就是 G ( x ) G(x) G(x) 是已知的)࿰…...
DAY 47
三、通道注意力 3.1 通道注意力的定义 # 新增:通道注意力模块(SE模块) class ChannelAttention(nn.Module):"""通道注意力模块(Squeeze-and-Excitation)"""def __init__(self, in_channels, reduction_rat…...
1688商品列表API与其他数据源的对接思路
将1688商品列表API与其他数据源对接时,需结合业务场景设计数据流转链路,重点关注数据格式兼容性、接口调用频率控制及数据一致性维护。以下是具体对接思路及关键技术点: 一、核心对接场景与目标 商品数据同步 场景:将1688商品信息…...
智能在线客服平台:数字化时代企业连接用户的 AI 中枢
随着互联网技术的飞速发展,消费者期望能够随时随地与企业进行交流。在线客服平台作为连接企业与客户的重要桥梁,不仅优化了客户体验,还提升了企业的服务效率和市场竞争力。本文将探讨在线客服平台的重要性、技术进展、实际应用,并…...
【python异步多线程】异步多线程爬虫代码示例
claude生成的python多线程、异步代码示例,模拟20个网页的爬取,每个网页假设要0.5-2秒完成。 代码 Python多线程爬虫教程 核心概念 多线程:允许程序同时执行多个任务,提高IO密集型任务(如网络请求)的效率…...
C#学习第29天:表达式树(Expression Trees)
目录 什么是表达式树? 核心概念 1.表达式树的构建 2. 表达式树与Lambda表达式 3.解析和访问表达式树 4.动态条件查询 表达式树的优势 1.动态构建查询 2.LINQ 提供程序支持: 3.性能优化 4.元数据处理 5.代码转换和重写 适用场景 代码复杂性…...
Proxmox Mail Gateway安装指南:从零开始配置高效邮件过滤系统
💝💝💝欢迎莅临我的博客,很高兴能够在这里和您见面!希望您在这里可以感受到一份轻松愉快的氛围,不仅可以获得有趣的内容和知识,也可以畅所欲言、分享您的想法和见解。 推荐:「storms…...
水泥厂自动化升级利器:Devicenet转Modbus rtu协议转换网关
在水泥厂的生产流程中,工业自动化网关起着至关重要的作用,尤其是JH-DVN-RTU疆鸿智能Devicenet转Modbus rtu协议转换网关,为水泥厂实现高效生产与精准控制提供了有力支持。 水泥厂设备众多,其中不少设备采用Devicenet协议。Devicen…...
消防一体化安全管控平台:构建消防“一张图”和APP统一管理
在城市的某个角落,一场突如其来的火灾打破了平静。熊熊烈火迅速蔓延,滚滚浓烟弥漫开来,周围群众的生命财产安全受到严重威胁。就在这千钧一发之际,消防救援队伍迅速行动,而豪越科技消防一体化安全管控平台构建的消防“…...
