自动合并从另一个集合引用的对象

本文关键字:引用 对象 集合 另一个 合并 | 更新日期: 2023-09-27 18:04:16

我想在一个文档中存储名为"Wsp"的对象,并在另一个文档中存储其名为"Sit"的属性之一。我阅读http://docs.mongodb.org/manual/core/data-modeling-introduction/,所以我创建了这样的结构:

    public class Wsp{
       public ObjectId Id{get; set;}
       public Guid WspId{get; set;}
       public List<Sit> SitList{get; set;}
       public string Name {get; set;}
       public ......... {get; set;}  
       }
       public class Sit{
             public ObjectId Id {get; set;}
             public Guid WspId;             //Id of a parent Wsp object
             public ......... {get; set;}  
       }
       //disabling Wsp from saving SitList into document (only Name, WspID and other..)
       BsonClassMap.RegisterClassMap<Wsp>(map =>
            {
              map.MapProperty(p => p.Name);
              map.MapProperty(p => p.WspId);
              ...
            });

现在我想创建GetWsp(Guid wspId)AddWsp(Wsp wsp),它们将自动将List of Sit映射到Wsp。例如:

public Wsp GetFullWsp(Guid id)
    {
        var wsp = wspCollection.AsQueryable().FirstOrDefault(w => w.WspId == id);
        //no code for List<Sit> !!
        //wsp will have List<Sit> automatic filled from "SitCollection" based on WspId
    }

如何配置这样的查询?我可以用BsonClassMap.RegisterClassMap吗?

这是一个好方法吗?还有其他建议吗?我读了关于MongoDBRef,但它被告知,性能下降使用它和性能对我来说是最重要的。

自动合并从另一个集合引用的对象

假设您已经有一个sitCollection:

public Wsp GetFullWsp(Guid id)
{
    var wsp = wspCollection.AsQueryable().FirstOrDefault(w => w.WspId == id);
    var sits = sitCollection.AsQueryable().Where(sit => sit.WspId == id);
    wsp.SitList = new List<Sit>(sits);
}

但是,我想你可能要考虑一下你的型号。我看到3个选项:

  1. 拥有单个wsps集合,并将sit列表存储为嵌入式文档数组。
  2. 添加SitListDocument集合,并将其Id存储在wsp文档中。
  3. 添加一个sit的集合(平面),其中每一个存储wsp文档id(这是接近你目前有,但没有一个SitList在wsp)

我会选择第一个,但这取决于你的具体需要。