【问题标题】:How to limit string field by characters in Aggregation?如何在聚合中按字符限制字符串字段?
【发布时间】:2022-12-12 16:14:04
【问题描述】:

我的文档看起来像这样:

[
{
   "_id" : ObjectId("5e41877df4cebbeaebec5146"),
   "title": "this is a title",
   "Paragraph" : "My Name is John Smith.I am learning MongoDB database"
},
{
   "_id" : ObjectId("5e4187d7f4cebbeaebec5147"),
   "title": "this is a title",
   "Paragraph" : "David Miller is a good student and learning Spring and Hibernate Framework."
}
]

我想将段落字段文本限制为 6 个字符,如下所示:

[
{
   "_id" : ObjectId("5e41877df4cebbeaebec5146"),
   "title": "this is a title",
   "Paragraph" : "My Nam"
},
{
   "_id" : ObjectId("5e4187d7f4cebbeaebec5147"),
   "title": "this is a title",
   "Paragraph" : "David "
}
]

我试过这段代码,但它删除了所有其他字段:

{
        $project:         {
            Paragraph: { $substr: [ "$Paragraph", 0, 6] }
            }      
}

【问题讨论】:

  • 使用$set而不是$project
  • @nimrodserok 谢谢

标签: mongodb mongodb-query aggregation-framework


【解决方案1】:
{
        $set:         {
            Paragraph: { $substr: [ "$Paragraph", 0, 6] }
            }      
}

【讨论】:

    猜你喜欢
    • 2022-12-06
    • 1970-01-01
    • 2014-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-14
    • 2020-12-17
    相关资源
    最近更新 更多