要从字符串中获得不同的第一个单词,可以使用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" ]