2013-06-25 73 views
0

我已经深深嵌入文档MongoDB中,像这样:MongoDB的C#驱动upserting嵌套文件

[ 
{ 
    id : 1, 
    stuff : [ 
      { 
      id : 1, 
      morestuff: [ 
         {id : 1, text : "foo"}, 
         {id : 2, text : "boo"} 
         ] 
      }, 
      { 
      id : 2, 
      morestuff: [ 
         {id : 1, text : "foo2"}, 
         {id : 2, text : "boo2"} 
         ] 
      } 
      ] 
} 
] 

我的C#的表示是这样的:

class CoreElement 
{ 
    public int id { get; set; } 
    public List<Stuff> stuff { get; set; } 
} 
class Stuff 
{ 
    public int id { get; set; } 
    public List<MoreStuff> morestuff { get; set; } 
} 
class MoreStuff 
{ 
    public int id { get; set; } 
    public string text { get; set; } 
} 

现在我可以有不同的情况:

  1. 给定ID的CoreElement不存在
  2. Stu FF与给定的ID不在CoreElement名单上
  3. MoreStuff不CoreElement

在功能的列表。如果我创建这样的一个对象:

CoreElement ce = new CoreElement(); 
ce.id = 1; 
Stuff st = new Stuff(); 
st.id = 2; 
MoreStuff ms = new MoreStuff(); 
ms.id = 17; 
ms.text = "something"; 
st.morestuff.Add(ms); 
ce.stuff.Add(st); 

有没有一种办法将它插入到我的集合中,以便在已存在的情况下将MoreStuff添加到相应的文档中,或者创建新文档(CoreElement或Stuff)(如果它尚不存在)?

任何帮助表示赞赏。谢谢。

+0

你用'$ push'试过了upsert吗? – WiredPrairie

回答

2

尝试用$addToSet

的$ addToSet运营商增加值到一个数组只有当值不是数组中了。如果该值在数组中,$ addToSet将返回而不修改数组。

你可以做的其他事情是加载你的CoreElement并在内存中使用它。你可以添加Suffs和MoreStuffs到检查C#重复项的对象。当你完成对象的保存时,MongoDB将用你修改的对象替换集合中的对象。