thu*_*eys 3 c# mongodb mongodb-query
我正在使用 c# 驱动程序,但我会很高兴使用任何语言的指针。
我的文档具有以下结构:
class Document
{
List<Comment> comments;
}
Run Code Online (Sandbox Code Playgroud)
或者用 Json 表示:
[{
"comments" : [{"comment" : "text1"}, {"comment" : "text2"}, ...]
},
{
"comments" : [{"comment" : "text1"}, {"comment" : "text2"}, ...]
}, ...]
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,每个文档都包含一个comments.
我的目标是运行一个定期任务,将每个文档的评论列表截断为特定数量的元素(例如 10)。
我想到的最明显的方法是:
是否有可能批量执行此操作Update?
我想不出更新的条件允许我在不先获取评论的情况下截断评论数量。
您可以将注释数组的元素切片到最后一个n元素(-10在下面的示例中)。在 shell 中尝试一下:
db.coll.update(
{ },
{ $push: { comments: { $each: [ ], $slice: -10 } } },
{ multi: true }
)
Run Code Online (Sandbox Code Playgroud)
从 MongoDB 2.6 开始,您还可以使用正数n来更新数组以仅包含第一个n元素。
如果您想在应用操作之前对某个字段进行排序slice:
db.coll.update(
{ }, {
$push: {
comments: {
$each: [ ],
$sort: { <field_to_sort_on>: 1 },
$slice: -10
}
}
},
{ multi: true }
)
Run Code Online (Sandbox Code Playgroud)