如何在 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" }
广告