数据结构如下:
{
"_id" : 0,
"name" : "aimee Zank",
"scores" : [
{
"type" : "exam",
"score" : 1.463179736705023
},
{
"type" : "quiz",
"score" : 11.78273309957772
},
{
"type" : "homework",
"score" : 6.676176060654615
},
{
"type" : "homework",
"score" : 35.8740349954354
}
]
}
最好是使用以下方法$pull使用过滤器,以便从数组中删除特定的分数。下面的代码使用MongoDBJava驱动程序v3.6和模型API
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import java.util.ArrayList;
import java.util.List;
import static com.mongodb.client.model.Updates.pull;
public class RemoveLowestScoreArray {
public static void main(String[] args) {
MongoDatabase database;
try (MongoClient client = new MongoClient()) {
database = client.getDatabase("school");
MongoCollection<Document> collection = database.getCollection("students");
List<Document> students = collection.find().into(new ArrayList<>());
for (Document student : students) {
Document lowestScore = null;
for (Document score : (List<Document>) student.get("scores")) {
if (score.getString("type").equals("homework")) {
if (lowestScore == null || score.getDouble("score") < (lowestScore.getDouble("score"))) {
lowestScore = score;
}
}
}
collection.updateOne(student, pull("scores", lowestScore));
}
}
}
}