如何使用 MongoDB 從字串中獲取去重的第一個單詞?


要從字串中獲取去重的第一個單詞,可以使用 distinct()。我們首先建立一個包含文件的集合 -

> db.distinctFirstWordDemo.insertOne(
   {
      "_id": 100,
      "StudentName":"John",
      "StudentFeature": "John is a good player",
      "Subject":"MongoDB"
   }
);
{ "acknowledged" : true, "insertedId" : 100 }
> db.distinctFirstWordDemo.insertOne(
   {
      "_id": 101,
      "StudentName":"Carol",
      "StudentFeature": "Carol is not a good player",
      "Subject":"MongoDB"
   }
);
{ "acknowledged" : true, "insertedId" : 101 }

使用 find() 方法顯示集合中的所有文件 -

> db.distinctFirstWordDemo.find().pretty();

這將生成以下輸出 -

{
   "_id" : 100,
   "StudentName" : "John",
   "StudentFeature" : "John is a good player",
   "Subject" : "MongoDB"
}
{
   "_id" : 101,
   "StudentName" : "Carol",
   "StudentFeature" : "Carol is not a good player",
   "Subject" : "MongoDB"
}

以下是從字串中獲取去重第一個單詞的查詢 -

> student = db.distinctFirstWordDemo.distinct("StudentFeature", {"Subject" : "MongoDB"}).map(function(st){
   return st.split(" ")[0];
});
[ "John", "Carol" ]
> printjson(student);

這將生成以下輸出 -

[ "John", "Carol" ]

更新於: 2019 年 7 月 30 日

164 次瀏覽

開啟你的職業生涯

完成課程並獲得認證

開始
廣告
© . All rights reserved.