借助 MongoDB 获取字符串中的第一个不同单词?


要想获取字符串中的首个不重复的单词,可使用 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" ]

更新时间: 31-Mar-2020

118 次浏览

开始您的 职业

完成该课程以获得认证

开始吧
广告
© . All rights reserved.