如何限制 MongoDB 查询中某个字段返回的字符数?

mongodbdatabasebig data analytics

为此,可以使用 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();

This will produce the following document −

{
   "_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" }

相关文章