如何使用 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" ]
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP