如何在 MongoDB 中限制欄位返回的字元數?


要限制從 MongoDB 欄位返回的字元數,請使用 $substr。讓我們建立一個包含文件的集合 -

> db.demo233.insertOne({"Paragraph":"My Name is John Smith.I am learning MongoDB database"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e41877df4cebbeaebec5146")
}
> db.demo233.insertOne({"Paragraph":"David Miller is a good student and learning Spring and Hibernate Framework."});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e4187d7f4cebbeaebec5147")
}

藉助 find() 方法顯示集合中的所有文件 -

> db.demo233.find().pretty();

這將產生以下輸出 -

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

以下是限制 MongoDB 中欄位返回的字元數的查詢 -

> db.demo233.aggregate(
...   [
...      {
...         $project:
...         {
...            Paragraph: { $substr: [ "$Paragraph", 0, 10] }
...
...      }
...} ] )

這將產生以下輸出 -

{ "_id" : ObjectId("5e41877df4cebbeaebec5146"), "Paragraph" : "My Name is" }
{ "_id" : ObjectId("5e4187d7f4cebbeaebec5147"), "Paragraph" : "David Mill" }

更新日期:2020 年 3 月 30 日

380 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.