【问题标题】:Truncating a list in MongoDb在 MongoDb 中截断列表
【发布时间】:2014-05-02 14:52:37
【问题描述】:

我正在使用 c# 驱动程序,但我对任何语言的指针都很满意。

我的文档具有以下结构:

 class Document
 {
      List<Comment> comments;
 }

或者在 Json 中:

 [{
     "comments" : [{"comment" : "text1"}, {"comment" : "text2"}, ...]
  },
  {
     "comments" : [{"comment" : "text1"}, {"comment" : "text2"}, ...]
  }, ...]

如您所见,每个文档都包含comments 的列表。

我的目标是运行一个周期性任务,将每个文档的 cmets 列表截断为特定数量的元素(例如 10)。

我想到的明显方法是:

  • 获取每个文档
  • 获取应删除的 cmets
  • 通过拉取应删除的 cmets 的 id 来按其 id 更新文档

是否有可能批量处理Update

我想不出一个更新条件,允许我在不先获取它们的情况下截断 cmets 的数量。

【问题讨论】:

    标签: c# mongodb mongodb-query


    【解决方案1】:

    您可以将 cmets 数组的元素切片到最后一个 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 }
    )
    

    【讨论】:

    • 谢谢,成功了!现在我必须找出如何使用 c# 驱动程序来做到这一点:P
    猜你喜欢
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    • 2012-08-25
    • 1970-01-01
    • 2021-09-22
    • 1970-01-01
    • 2015-07-11
    • 1970-01-01
    相关资源
    最近更新 更多