使用C#驱动程序更新/删除mongodb中的子文档 [英] Update/Delete a sub document in mongodb using C# driver
本文介绍了使用C#驱动程序更新/删除mongodb中的子文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有2个课程:
public class Vote
{
public string VoteId { get; set; }
public string Question { get; set; }
public List<VoteAnswer> AnswerList { get; set; }
}
并且:
public class VoteOption
{
public string OptionId { get; set; }
public string OptionName { get; set; }
public double VoteCount { get; set; }
}
如何在VoteId = voteId
和OptionId = optionId
所在的Vote
中更新/删除VoteOption
?使用C#
驱动程序.
How can i update/delete a VoteOption
in a Vote
where VoteId = voteId
and OptionId = optionId
? Using C#
driver.
首先,我通过以下方式获得VoteOption:
First I get VoteOption by:
var v = col.FindOneAs<Vote>(Query.EQ("VoteID", voteId));
VoteOption vo = v.AnswerList.Find(x => x.OptionId == optionId);
为它设置一些值:
vo.OptionName = "some option chose";
vo.VoteCount = 1000;
但是我不知道下一步要将此vo
更新为Vote parent
.
But i don't know what next step to update this vo
to Vote parent
.
而且,如果我想删除此vo
,请以这种方式告诉我!
And, if i want to delete this vo
, show me that way!
像这样的MongoDB中的数据:
Data in MongoDB like that:
{
"_id" : "460b3a7ff100",
"Question" : "this is question?",
"AnswerList" : [{
"OptionId" : "1",
"OptionName" : "Option 1",
"VoteCount" : 0.0
}, {
"OptionId" : "2",
"OptionName" : "Option 2",
"VoteCount" : 0.0
}, {
"OptionId" : "3",
"OptionName" : "Option 3",
"VoteCount" : 0.0
}
}]
}
推荐答案
要更新子文档,您可以使用以下方法:
To update subdocument you can use this:
var update = Update.Set("AnswerList.$.OptionName", "new").Set("AnswerList.$.VoteCount", 5);
collection.Update(Query.And(Query.EQ("_id", new BsonObjectId("50f3c313f216ff18c01d1eb0")), Query.EQ("AnswerList.OptionId", "1")), update);
分析器:
"query" : { "_id" : ObjectId("50f3c313f216ff18c01d1eb0"), "AnswerList.OptionId" : "1" },
"updateobj" : { "$set" : { "AnswerList.$.OptionName" : "new", "AnswerList.$.VoteCount" : 5 } }
并删除:
var pull = Update<Vote>.Pull(x => x.AnswerList, builder => builder.EQ(q => q.OptionId, "2"));
collection.Update(Query.And(Query.EQ("_id", new BsonObjectId("50f3c313f216ff18c01d1eb0")), Query.EQ("AnswerList.OptionId", "2")), pull);
分析器:
"query" : { "_id" : ObjectId("50f3c313f216ff18c01d1eb0"), "AnswerList.OptionId" : "2" },
"updateobj" : { "$pull" : { "AnswerList" : { "OptionId" : "2" } } }
另一种方法是使用修改后的子集合来更新父文档.
Another way is to update parent document with modified child collection.
这篇关于使用C#驱动程序更新/删除mongodb中的子文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文