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

개체 배열에서 빈 개체를 제거하는 MongoDB 쿼리?

<시간/>

이를 위해 $pull 연산자를 사용할 수 있습니다. 먼저 문서로 컬렉션을 생성해 보겠습니다. 여기에 빈 객체도 추가했습니다 -

> db.removeEmptyObjectsDemo.insertOne(
   {
      "_id" :101,
      "LoginDate" :new ISODate(),
      "UserDetails" : [
         {
            "UserName" : "John"
         },
         {
         },
         {
            "UserName" : "Sam"
         }
      ]
   }
);
{ "acknowledged" : true, "insertedId" : 101 }

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

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

이것은 다음과 같은 출력을 생성합니다 -

{
   "_id" : 101,
   "LoginDate" : ISODate("2019-05-25T04:46:29.505Z"),
   "UserDetails" : [
      {
         "UserName" : "John"
      },
      {
      },
      {
         "UserName" : "Sam"
      }
   ]
}

다음은 개체 배열에서 빈 개체를 제거하는 쿼리입니다 -

> db.removeEmptyObjectsDemo.update(
{},
{ "$pull": { "UserDetails": { "UserName": { "$exists": false } } } },
{ "multi": true }
);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

위 컬렉션의 문서를 확인합시다 -

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

그러면 다음과 같은 출력이 생성됩니다. 빈 개체가 성공적으로 제거되었습니다 -

{
   "_id" : 101,
   "LoginDate" : ISODate("2019-05-25T04:46:29.505Z"),
   "UserDetails" : [
      {
         "UserName" : "John"
      },
      {
         "UserName" : "Sam"
      }
   ]
}