使用 MongoDB 获取字符串中不同的首词?

mongodbdatabasebig data analytics更新于 2026/1/10 7:07:17

要获取字符串中不同的首词,请使用 split()。首先,我们创建一个包含文档的集合。 −

> db.demo129.insertOne({"Words":"This is the MySQL","CountryName":"US"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e305d6368e7f832db1a7f6b")
}
> db.demo129.insertOne({"Words":"MongoDB is NOSQL database","CountryName":"US"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e305d7b68e7f832db1a7f6c")
}

借助 find() 方法显示集合中的所有文档 −

> db.demo129.find();

这将产生以下输出 −

{ "_id" : ObjectId("5e305d6368e7f832db1a7f6b"), "Words" : "This is the MySQL", "CountryName" : "US" }
{ "_id" : ObjectId("5e305d7b68e7f832db1a7f6c"), "Words" : "MongoDB is NOSQL database", "CountryName" : "US" }

以下查询用于获取字符串中不同的首单词 −

> w = db.demo129.distinct("Words", {"CountryName" : "US"}).map(function(doc){ return doc.split(" ")[0]; });
[ "This", "MongoDB" ]

现在您可以借助 printjson() 进行显示。

> printjson(w);

这将产生以下输出 −

[ "This", "MongoDB" ]

相关文章