Computer >> 컴퓨터 >  >> 프로그램 작성 >> MongoDB

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" ]