MongoDB
 Computer >> コンピューター >  >> プログラミング >> MongoDB

MongoDBの配列からオブジェクトを削除しますか?


MongoDBの配列からオブジェクトを削除するには、$pull演算子を使用できます。構文は次のとおりです。

db.yourCollectionName.update( {'_id':ObjectId("5c6ea036a0c51185aefbd14f")},
{$pull:{"yourArrayName":{"yourArrayFieldName":yourValue}}},
false,true);

上記の構文を理解するために、ドキュメントを使用してコレクションを作成しましょう。ドキュメントを使用してコレクションを作成するためのクエリは次のとおりです。

> db.removeObject.insertOne({"CustomerName":"Maxwell","CustomerAge":23,
... "CustomerDetails":[
... {
... "CustomerId":100,
... "CustomerProduct":"Product-1"
... },
... {
... "CustomerId":150,
... "CustomerProduct":"Product-2"
... },
... {
... "CustomerId":200,
... "CustomerProduct":"Product-3"
... }
... ]
... });
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c6ea036a0c51185aefbd14f")
}

find()メソッドを使用して、コレクションのすべてのドキュメントを表示します。クエリは次のとおりです。

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

出力は次のとおりです。

{
   "_id" : ObjectId("5c6ea036a0c51185aefbd14f"),
   "CustomerName" : "Maxwell",
   "CustomerAge" : 23,
   "CustomerDetails" : [
      {
         "CustomerId" : 100,
         "CustomerProduct" : "Product-1"
      },
      {
         "CustomerId" : 150,
         "CustomerProduct" : "Product-2"
      },
      {
         "CustomerId" : 200,
         "CustomerProduct" : "Product-3"
      }
   ]
}

MongoDBの配列からオブジェクトを削除するためのクエリは次のとおりです。

> db.removeObject.update( {'_id':ObjectId("5c6ea036a0c51185aefbd14f")},
... {$pull:{"CustomerDetails":{"CustomerId":150}}},
... false,true);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

上記では、配列からオブジェクトを削除しました。コレクションのドキュメントを表示してみましょう。クエリは次のとおりです。

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

出力は次のとおりです。

{
   "_id" : ObjectId("5c6ea036a0c51185aefbd14f"),
   "CustomerName" : "Maxwell",
   "CustomerAge" : 23,
   "CustomerDetails" : [
      {
         "CustomerId" : 100,
         "CustomerProduct" : "Product-1"
      },
      {
         "CustomerId" : 200,
         "CustomerProduct" : "Product-3"
      }
   ]
}

  1. コレクションから配列全体を削除するMongoDBクエリ?

    コレクションから配列全体を削除するには、MongoDBで$unsetを使用します。ドキュメントを使用してコレクションを作成しましょう- > db.demo609.insertOne({"ListOfSubject":["MySQL","MongoDB"]});{    "acknowledged" : true, "insertedId" : ObjectId("5e974695f57d0dc0b182d62c") } > db.demo609

  2. PHP:配列からオブジェクトを削除します

    unset関数を使用して、PHPの特定のインデックスから配列オブジェクトを削除できます- 例 $index = 2; $objectarray = array(    0 => array('label' => 'abc', 'value' => 'n23'),    1 => array('label' => 'def', 'value' => '2n13'),    2