我正在使用c#驱动程序,但我会对使用任何语言的指针感到高兴。
我的文件具有以下结构:
class Document
{
List<Comment> comments;
}
或者在Json:
[{
"comments" : [{"comment" : "text1"}, {"comment" : "text2"}, ...]
},
{
"comments" : [{"comment" : "text1"}, {"comment" : "text2"}, ...]
}, ...]
如您所见,每个文档都包含comments
的列表。
我的目标是运行一个周期性任务,将每个文档的注释列表截断为特定数量的元素(例如10)。
我想到的显而易见的方法是:
是否有可能使用批量Update
执行此操作?
我无法想到更新的条件,我可以在不先获取注释的情况下截断注释的数量。
答案 0 :(得分:2)
您可以将comments数组的元素切片到最后的n
元素(下例中的-10
)。在shell中试试这个:
db.coll.update(
{ },
{ $push: { comments: { $each: [ ], $slice: -10 } } },
{ multi: true }
)
从MongoDB 2.6开始,您也可以使用肯定n
来更新数组,使其仅包含第一个n
元素。
如果您在应用slice
操作之前有一个要排序的字段:
db.coll.update(
{ }, {
$push: {
comments: {
$each: [ ],
$sort: { <field_to_sort_on>: 1 },
$slice: -10
}
}
},
{ multi: true }
)