我正在创建一个开源社交网络(我不知道是否可以在此处发布 URL),使用 .net core 2.1,mongo atlas 使用驱动程序 v2.9.2
我正在从 MS SQL(我知道如何对其进行操作)迁移到 mongo(我仍在学习)。
我有两个实体,UserContent 和 UserContentComment,都继承自 Entity:
public class Entity
{
public Guid Id { get; set; }
public Guid UserId { get; set; }
public DateTime CreateDate { get; set; }
public Entity()
{
CreateDate = DateTime.Now;
}
}
public class UserContent : Entity
{
public string AuthorName { get; set; }
public string Content { get; set; }
public virtual List<UserContentComment> Comments { get; set; }
}
public class UserContentComment : Entity
{
public Guid UserContentId { get; set; }
public string AuthorName { get; set; }
public string Text { get; set; }
}
我可能会清理一些属性,因为我不再需要它们,例如 UserContentId,因为我将 UserContentComments 添加为 UserContent 的嵌套数组“Comments”,如下所示:
{
"_id" : UUID("ff6e86cc-bddf-419d-e049-08d6b903e6db"),
"_t" : [
"Entity",
"UserContent"
],
"userId" : UUID("9d6e26ca-5bc7-4121-9b03-ed7f9a442cf6"),
"createDate" : ISODate("2019-04-04T16:38:23.740-03:00"),
"authorName" : "User Full Name",
"content" : "content main text",
"comments" : [
{
"_t" : [
"Entity",
"UserContentComment"
],
"_id" : UUID("d7dc1328-b1bc-4f1f-a9a5-08d6bf05b672"),
"userId" : UUID("5f9eeb34-22e2-43bf-9130-034a7997d2af"),
"createDate" : ISODate("2019-04-12T05:15:20.636-03:00"),
"userContentId" : UUID("ff6e86cc-bddf-419d-e049-08d6b903e6db"),
"authorName" : "User Full Name",
"text" : "Hello from Russia!"
}
]
}
我的问题是我需要:
- 按用户 ID 统计评论数;
- 通过 UserId 获取评论;
- 通过 Id 获取单个评论;
- 按 ID 更新单个评论;
- 通过 UserId 更新所有评论;
如何使用 C# 的 mongodb 驱动程序来实现这一点?
非常感谢你的帮助!
更新 - 到目前为止我得到了什么
为了统计评论,我通过三种方式获得:
var count = DbSet.Aggregate()
.Match(x => x.Comments.Any(y => y.UserId == userId))
.Project(new BsonDocument("count", new BsonDocument("$size", "$comments"))).ToList();
var q = Builders<UserContent>.Filter.ElemMatch(x => x.Comments, d => d.UserId == userId);
var p = Builders<UserContent>.Projection.ElemMatch(x => x.Comments, d => d.UserId == userId);
var data = DbSet.Find(q).Project(p).ToList();
var data2 = DbSet.Find(q).ToList();
这三个不同的查询,返回28,因为用户确实评论了28个帖子,但数据库上总共有31条评论,因为用户对某些帖子评论了多次。我在这里缺少什么?
现在更新 COUNT 有效
我使用以下代码进行了计数:
DbSet.AsQueryable().SelectMany(x => x.Comments).Where(where).Count();
我使用上面的代码得到了 31,现在是正确的!
现在的问题是:它会在内存上还是在数据库上运行?