为此,请使用MongoDB $substr。首先让我们创建一个包含文档的集合-
> dblimitTheNumberOfCharactersDemoinsertOne({"Title":"MongoDB is No SQL database"}); { "acknowledged" : true, "insertedId" : ObjectId("5cf23013b64a577be5a2bc0e") } > dblimitTheNumberOfCharactersDemoinsertOne({"Title":"MySQL is a relational database"}); { "acknowledged" : true, "insertedId" : ObjectId("5cf2302db64a577be5a2bc0f") }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> dblimitTheNumberOfCharactersDemofind()pretty();
这将产生以下文件-
{ "_id" : ObjectId("5cf23013b64a577be5a2bc0e"), "Title" : "MongoDB is No SQL database" } { "_id" : ObjectId("5cf2302db64a577be5a2bc0f"), "Title" : "MySQL is a relational database" }
以下是限制从MongoDB查询中的字段返回的字符数量的查询-
> dblimitTheNumberOfCharactersDemoaggregate( [ { $project: { Characters: { $substr: [ "$Title", 0, 20 ] } } } ] );
这将产生以下文件-
{ "_id" : ObjectId("5cf23013b64a577be5a2bc0e"), "Characters" : "MongoDB is No SQL da" } { "_id" : ObjectId("5cf2302db64a577be5a2bc0f"), "Characters" : "MySQL is a relationa" }