藉助 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.