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

두 필드의 문자열을 MongoDB의 세 번째 필드로 연결하시겠습니까?

<시간/>

두 필드의 문자열을 세 번째 필드로 연결하려면 다음 구문을 사용할 수 있습니다.

db.yourCollectionName.aggregate(
   [
      { $project: { "yourNewFieldName": { $concat: [ "$yourFieldName1", " yourDellimiterValue ", "$yourFieldName2" ] } } }
   ]
);

먼저 문서로 컬렉션을 생성하겠습니다.

>db.concatenateStringsDemo.insertOne({"StudentFirstName":"John","StudentLastName":"Doe"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9bb7362d66697741252444")
}
>db.concatenateStringsDemo.insertOne({"StudentFirstName":"John","StudentLastName":"Smith"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9bb7402d66697741252445")
}
>db.concatenateStringsDemo.insertOne({"StudentFirstName":"Carol","StudentLastName":"Taylor"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9bb74c2d66697741252446")
}
>db.concatenateStringsDemo.insertOne({"StudentFirstName":"David","StudentLastName":"Miller"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9bb7752d66697741252447")
}
>db.concatenateStringsDemo.insertOne({"StudentFirstName":"James","StudentLastName":"Williams"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9bb7862d66697741252448")
}

다음은 find() 메서드를 사용하여 컬렉션의 모든 문서를 표시하는 쿼리입니다.

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

그러면 다음과 같은 출력이 생성됩니다.

{
   "_id" : ObjectId("5c9bb7362d66697741252444"),
   "StudentFirstName" : "John",
   "StudentLastName" : "Doe"
}
{
   "_id" : ObjectId("5c9bb7402d66697741252445"),
   "StudentFirstName" : "John",
   "StudentLastName" : "Smith"
}
{
   "_id" : ObjectId("5c9bb74c2d66697741252446"),
   "StudentFirstName" : "Carol",
   "StudentLastName" : "Taylor"
}
{
   "_id" : ObjectId("5c9bb7752d66697741252447"),
   "StudentFirstName" : "David",
   "StudentLastName" : "Miller"
}
{
   "_id" : ObjectId("5c9bb7862d66697741252448"),
   "StudentFirstName" : "James",
   "StudentLastName" : "Williams"
}

다음은 두 필드의 문자열을 세 번째 필드로 연결하는 쿼리입니다. 여기에서 "StudentFirstName" 및 "StudentLastName" 필드를 세 번째 필드로 연결합니다.

> db.concatenateStringsDemo.aggregate(
... [
... { $project: { "StudentFullName": { $concat: [ "$StudentFirstName", " / ", "$StudentLastName" ] } } }
... ]
... );

그러면 다음과 같은 출력이 생성됩니다.

{ "_id" : ObjectId("5c9bb7362d66697741252444"), "StudentFullName" : "John / Doe" }
{ "_id" : ObjectId("5c9bb7402d66697741252445"), "StudentFullName" : "John / Smith" }
{ "_id" : ObjectId("5c9bb74c2d66697741252446"), "StudentFullName" : "Carol / Taylor" }
{ "_id" : ObjectId("5c9bb7752d66697741252447"), "StudentFullName" : "David / Miller" }
{ "_id" : ObjectId("5c9bb7862d66697741252448"), "StudentFullName" : "James / Williams" }