C# 限制mongodb c中嵌套数组的大小#
我有一个mongodb对象,看起来像这样:C# 限制mongodb c中嵌套数组的大小#,c#,mongodb,C#,Mongodb,我有一个mongodb对象,看起来像这样: { "_id" : "5a567ef6992fb9020474f72d", "groupName" : "test, admin, binky, water, brick", "users" : [ "test", "admin", "binky", "water", "brick" ], "comments" : [
{
"_id" : "5a567ef6992fb9020474f72d",
"groupName" : "test, admin, binky, water, brick",
"users" : [
"test",
"admin",
"binky",
"water",
"brick"
],
"comments" : [
{
"comment" : "test message",
"createdBy" : "admin",
"createdAt" : ISODate("2018-01-11T00:01:59.672Z")
},
{
"comment" : "test message",
"createdBy" : "admin",
"createdAt" : ISODate("2018-01-11T00:02:48.237Z")
}
],
"createdBy" : "admin"
}
所以,我的问题是,我不希望评论的数量无限增长。我希望能够限制可能的评论数量
插入时是否需要查看评论的数量,然后删除超过100条的前几条?假设我们到了101,它会删除第一个对象
我添加注释的代码是:
var coll = DatabaseCommon.Instance.GetDatabase("ps_" + siteId).GetCollection<Group>("chatgroups");
var currentGroup = coll.FindOneAndUpdate(y => y._id == groupId, Builders<Group>.Update.Push<Comment>(y => y.comments, comment));
var coll=DatabaseCommon.Instance.GetDatabase(“ps_389;”+siteId.GetCollection(“chatgroups”);
var currentGroup=coll.FindOneAndUpdate(y=>y._id==groupId,Builders.Update.Push(y=>y.comments,comment));
我试过:
var coll = DatabaseCommon.Instance.GetDatabase("ps_" + siteId).GetCollection<Group>("chatgroups");
coll.UpdateOne({ _id: groupId }, { $push: { comments: { $each: [comment], $slice: -100 } } });
var coll=DatabaseCommon.Instance.GetDatabase(“ps_389;”+siteId.GetCollection(“chatgroups”);
coll.UpdateOne({u id:groupId},{$push:{comments:{$each:[comment],$slice:-100}});
但我在编译时总是出错,说它期待着另一个接近的参数
您可以使用$slice实现这一点 此外,如果您不想删除任何注释,但只想限制单个文档中的数组大小,则可以使用一种称为“Bucketing”的有用技术。这里有一个问题概述了C语言的技术和语法#
因此,我通过四个步骤解决了这个问题。首先,找到记录:
var coll = DatabaseCommon.Instance.GetDatabase("ps_" + siteId).GetCollection<Group>("chatgroups");
var record = coll.Find(y => y._id == groupId).Single();
然后,仅获取最后100条评论:
record.comments = record.comments.Skip(Math.Max(0, record.comments.Count - 100)).ToList();
保存更改的记录:
coll.ReplaceOne(y => y._id == groupId, record);
与同时删除注释相比,添加新注释是微不足道的。但是,如果存储引用根对象的注释,则有更多选项,因为可以将查询限制为仅包含最新的N条注释,并且可以将删除旧注释作为后台服务器任务执行,而不是在每次插入时执行。很明显,这是一种折衷。谢谢你提供的信息。很抱歉耽搁了你,我在做其他事情时被抓住了。我知道我可以使用$slice,但我似乎无法在我的c代码中使用它,它总是会产生错误。你有什么例子吗?你能用你的代码和你得到的错误来更新你的问题吗?所以,我终于回到这里了。我附加了错误,总是想关闭parens,你看到问题了吗?我解决了它,但也许你有一个更好的主意,可以一步完成它并使操作更快???:var coll=DatabaseCommon.Instance.GetDatabase(“ps_”+siteId”).GetCollection(“chatgroups”);var record=coll.Find(y=>y._id==groupId).Single();记录。评论。添加(评论);record.comments=record.comments.Skip(Math.Max(0,record.comments.Count-100)).ToList();coll.ReplaceOne(y=>y._id==groupId,记录);
coll.ReplaceOne(y => y._id == groupId, record);