MongoDBの配列からオブジェクトを削除するにはどうすればよいですか?
$ pull演算子を使用して、MongoDBの配列からオブジェクトを削除できます。概念を理解するために、ドキュメントを使用してコレクションを作成しましょう。ドキュメントを使用してコレクションを作成するためのクエリは次のとおりです-
> db.removeObjectFromArrayDemo.insertOne(
... {
...
... "StudentName": "John",
... "StudentAcademicProjectDetails":
... [{
... "StudentProjectId": 101,
... "StudentProjectName": "Pig Dice Game"
... },
... {
... "StudentProjectId": 110,
... "StudentProjectName": "Library Management System"
... },
...
... {
... "StudentProjectId": 120,
... "StudentProjectName": "Phonebook Management System"
... }
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5c8ad13d6cea1f28b7aa0817")
} find()メソッドを使用して、コレクションのすべてのドキュメントを表示します。クエリは次のとおりです-
> db.removeObjectFromArrayDemo.find().pretty();
以下は出力です-
{
"_id" : ObjectId("5c8ad13d6cea1f28b7aa0817"),
"StudentName" : "John",
"StudentAcademicProjectDetails" : [
{
"StudentProjectId" : 101,
"StudentProjectName" : "Pig Dice Game"
},
{
"StudentProjectId" : 110,
"StudentProjectName" : "Library Management System"
},
{
"StudentProjectId" : 120,
"StudentProjectName" : "Phonebook Management System"
}
]
} これは、MongoDBの配列からオブジェクトを削除するためのクエリです-
> db.removeObjectFromArrayDemo.update(
... {'_id': ObjectId("5c8ad13d6cea1f28b7aa0817")},
... { $pull: { "StudentAcademicProjectDetails" : { StudentProjectId: 101 } } },
... false,
... true
... );
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) コレクションからドキュメントをチェックして、オブジェクトが配列から削除されているかどうかを確認しましょう。クエリは次のとおりです-
> db.removeObjectFromArrayDemo.find().pretty();
以下は出力です-
{
"_id" : ObjectId("5c8ad13d6cea1f28b7aa0817"),
"StudentName" : "John",
"StudentAcademicProjectDetails" : [
{
"StudentProjectId" : 110,
"StudentProjectName" : "Library Management System"
},
{
"StudentProjectId" : 120,
"StudentProjectName" : "Phonebook Management System"
}
]
} 上記のサンプル出力を見ると、101のフィールド「StudentProjectId」が削除されています。
-
MongoDBコレクションから重複を削除するにはどうすればよいですか?
このために、「 unique:true」を設定します 」つまり、一意の制約を使用し、次の構文のように重複を挿入しないようにします- db.yourCollectionName.ensureIndex({yourFieldName: 1}, {unique: true, dropDups: true}) 上記の構文を理解するために、ドキュメントを使用してコレクションを作成しましょう。ここでは、重複挿入は許可されません- > db.demo604.ensureIndex({FirstName: 1}, {unique: true, dropDups: true});{ &nb
-
PHP:配列からオブジェクトを削除します
unset関数を使用して、PHPの特定のインデックスから配列オブジェクトを削除できます- 例 $index = 2; $objectarray = array( 0 => array('label' => 'abc', 'value' => 'n23'), 1 => array('label' => 'def', 'value' => '2n13'), 2