给出集合
{
"_id" : 137,
"name" : "Tamika Schildgen",
"scores" : [
{
"type" : "exam",
"score" : 4.433956226109692
},
{
"type" : "homework",
"score" : 65.50313785402548
},
{
"type" : "homework",
"score" : 89.5950384993947
}
]
};
如何从具有in集合的分数嵌入数组中删除具有最低score.type =“ homeowrk”值的分数?尝试使用下面的代码,但是没有运气,无法找到问题所在。
var col = db.GetCollection<BsonDocument>("students");
var pipeline = new BsonDocument[] {
new BsonDocument{{"$unwind", "$scores"}},
new BsonDocument{ {"$match",new BsonDocument { {
"scores.type", "homework" } } } },
new BsonDocument{{"$group", new BsonDocument{
{"_id", "$_id"},
{"lowscore",new BsonDocument{
{"$min","$scores.score"}}
}}
}}
};
var result = await col.Aggregate<BsonDocument>(pipeline).ToListAsync();
在这里,我得到的结果是正确的,作业类型得分很低,但是以下更新并未从收藏夹中删除项目,因此我无法弄清楚。
foreach (var doc in result)
{
var filterS = new BsonDocument("_id", doc.GetElement("_id").Value.ToInt32());
var update = Builders<BsonDocument>.Update.PullFilter("scores",
Builders<BsonDocument>.Filter.Eq("scores.score", doc.GetElement("lowscore").Value.ToDecimal128()));
var mresult = col.FindOneAndUpdateAsync(filterS, update).Result;
Console.WriteLine(mresult);
}