문자열에서 고유한 첫 번째 단어를 얻으려면 고유한()을 사용할 수 있습니다. 먼저 문서로 컬렉션을 생성해 보겠습니다. −
> 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" ]