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

Mongodb의 배열 내부 문서에서 특정 필드를 투영하는 방법은 무엇입니까?

<시간/>

배열 내부의 문서에서 특정 필드를 투영하려면 위치($) 연산자를 사용할 수 있습니다.

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

> db.projectSpecificFieldDemo.insertOne(
   ... {
      ... "UniqueId": 101,
      ... "StudentDetails" : [{"StudentName" : "Chris", "StudentCountryName ": "US"},
         ... {"StudentName" : "Robert", "StudentCountryName" : "UK"},
      ... ]
      ... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ca27aeb6304881c5ce84ba2")
}
> db.projectSpecificFieldDemo.insertOne( { "UniqueId": 102, "StudentDetails" :
   [{"StudentName" : "Robert", "StudentCountryName ": "UK"}, {"StudentName" : "David",
   "StudentCountryName" : "AUS"}, ] } );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ca27b106304881c5ce84ba3")
}

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

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

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

{
   "_id" : ObjectId("5ca27aeb6304881c5ce84ba2"),
   "UniqueId" : 101,
   "StudentDetails" : [
      {
         "StudentName" : "Chris",
         "StudentCountryName " : "US"
      },
      {
         "StudentName" : "Robert",
         "StudentCountryName" : "UK"
      }
   ]
}
{
   "_id" : ObjectId("5ca27b106304881c5ce84ba3"),
   "UniqueId" : 102,
   "StudentDetails" : [
      {
         "StudentName" : "Robert",
         "StudentCountryName " : "UK"
      },
      {
         "StudentName" : "David",
         "StudentCountryName" : "AUS"
      }
   ]
}

다음은 배열 내부의 문서에서 특정 필드를 투영하는 쿼리입니다.

> var myDocument = { UniqueId : 101, 'StudentDetails.StudentName' : 'Chris' };
> var myProjection= {'StudentDetails.$': 1 };
> db.projectSpecificFieldDemo.find(myDocument , myProjection).pretty();

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

{
   "_id" : ObjectId("5ca27aeb6304881c5ce84ba2"),
   "StudentDetails" : [
      {
         "StudentName" : "Chris",
         "StudentCountryName " : "US"
      }
   ]
}