Database Manual / Reference / Query Language / Update / Arrays

$pull (update operator)(更新运算符)

$pull
The $pull operator removes from an existing array all instances of a value or values that match a specified condition.$pull运算符从现有数组中删除与指定条件匹配的一个或多个值的所有实例。

Compatibility兼容性

You can use $pull for deployments hosted in the following environments:您可以将$pull用于在以下环境中托管的部署:

  • MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud:云中MongoDB部署的完全托管服务
  • MongoDB Enterprise: The subscription-based, self-managed version of MongoDB:MongoDB的基于订阅的自我管理版本
  • MongoDB Community: The source-available, free-to-use, and self-managed version of MongoDB:MongoDB的源代码可用、免费使用和自我管理版本

Syntax语法

The $pull operator has the following form:$pull运算符具有以下形式:

{ $pull: { <field1>: <value|condition>, <field2>: <value|condition>, ... } }

To specify a <field> in an embedded document or in an array, use dot notation.要在嵌入式文档或数组中指定<field>,请使用点符号

Behavior行为

Starting in MongoDB 5.0, update operators process document fields with string-based names in lexicographic order. Fields with numeric names are processed in numeric order. See Update Operators Behavior for details.从MongoDB 5.0开始,更新运算符按字典顺序处理具有基于字符串的名称的文档字段。具有数字名称的字段按数字顺序处理。有关详细信息,请参阅更新运算符行为

If you specify a <condition> and the array elements are embedded documents, $pull operator applies the <condition> as if each array element were a document in a collection. See Remove All Items That Match a Specified $pull Condition With bulkWrite() for an example.如果您指定了一个<condition>,并且数组元素是嵌入式文档,则$pull运算符会应用<condition>,就像每个数组元素都是集合中的文档一样。有关示例,请参阅使用bulkWrite()删除与指定$pull条件匹配的所有项目

If the specified <value> to remove is an array, $pull removes only the elements in the array that match the specified <value> exactly, including order.如果要删除的指定<value>是一个数组,则$pull仅删除数组中与指定的<value>完全匹配的元素,包括顺序。

If the specified <value> to remove is a document, $pull removes only the elements in the array that have the exact same fields and values. The ordering of the fields can differ.如果要删除的指定<value>是文档,则$pull仅删除数组中具有完全相同字段和值的元素。字段的顺序可能不同。

Starting in MongoDB 5.0, mongod no longer raises an error when you use an update operator like $pull with an empty operand expression ( { } ). An empty update results in no changes and no oplog entry is created (meaning that the operation is a no-op).从MongoDB 5.0开始,当您使用带有空操作数表达式({ })的$pull等更新运算符时,mongod不再引发错误。空更新不会导致任何更改,也不会创建oplog条目(这意味着该操作是无操作)。

Examples示例

Remove All Items That Equal a Specified Value删除等于指定值的所有项目

Create the stores collection:创建stores集合:

db.stores.insertMany( [
{
_id: 1,
fruits: [ "apples", "pears", "oranges", "grapes", "bananas" ],
vegetables: [ "carrots", "celery", "squash", "carrots" ]
},
{
_id: 2,
fruits: [ "plums", "kiwis", "oranges", "bananas", "apples" ],
vegetables: [ "broccoli", "zucchini", "carrots", "onions" ]
}
] )

The following operation removes以下操作将删除

  • "apples" and "oranges" from the fruits arrayfruits数组中的"apples""oranges"
  • "carrots" from the vegetables arrayvegetables数组中的"carrots"(胡萝卜)
db.stores.updateMany(
{ },
{ $pull: { fruits: { $in: [ "apples", "oranges" ] }, vegetables: "carrots" } }
)

Confirm the result with db.collection.find():使用db.collection.find()确认结果:

{
_id: 1,
fruits: [ 'pears', 'grapes', 'bananas' ],
vegetables: [ 'celery', 'squash' ]
},
{
_id: 2,
fruits: [ 'plums', 'kiwis', 'bananas' ],
vegetables: [ 'broccoli', 'zucchini', 'onions' ]
}

Remove All Items That Match a Specified $pull Condition删除符合指定$pull条件的所有项目

Create the profiles collection:创建profiles集合:

db.profiles.insertOne( { _id: 1, votes: [ 3, 5, 6, 7, 7, 8 ] } )

The following operation will remove all items from the votes array that are greater than or equal to ( $gte ) 6:以下操作将从votes数组中删除大于或等于($gte)6的所有项目:

db.profiles.updateOne( { _id: 1 }, { $pull: { votes: { $gte: 6 } } } )

After the update operation, the document only has values less than 6:更新操作后,文档中只有小于6的值:

{ _id: 1, votes: [  3,  5 ] }

Remove All Items That Match a Specified $pull Condition With bulkWrite()使用bulkWrite()删除与指定$pull条件匹配的所有项目

The following db.collection.bulkWrite() operation:以下db.collection.bulkWrite()操作:

  • Creates the profilesBulkWrite collection.创建profilesBulkWrite集合。
  • Removes all items from the votes array that are greater than or equal to ( $gte ) 6.votes数组中删除大于或等于($gte6的所有项目。
  • Removes all items from the votes array that are less than or equal to ( $lte ) 3.votes数组中删除小于或等于($lte3的所有项目。
try {
db.profilesBulkWrite.bulkWrite( [
{
insertOne: {
"document": { _id: 1, votes: [ 3, 5, 6, 7, 7, 8 ] }
}
},
{
updateOne: {
"filter": { _id: 1 },
"update": { $pull: { votes: { $gte: 6 } } }
}
},
{
updateOne: {
"filter": {_id: 1},
"update": { $pull: { votes: { $lte: 3 } } }
}
}
] );
} catch (e) {
print(e);
}

Note

bulkWrite()

The db.collection.bulkWrite() method executes multiple write operations listed in an array. db.collection.bulkWrite()方法执行数组中列出的多个写入操作。In this example, the db.collection.bulkWrite() performs multiple operations on the profiles collection.在此示例中,db.collection.bulkWrite()对配置文件集合执行多个操作。

After the db.collection.bulkWrite() operation, you can confirm the document only has values less than 6 and greater than 3 using the following operation:db.collection.bulkWrite()操作之后,您可以使用以下操作确认文档只有小于6且大于3的值:

db.profilesBulkWrite.find()

The operation returns the following:该操作返回以下内容:

[ { _id: 1, votes: [ 5 ] } ]

Remove Items from an Array of Documents从文档数组中删除项目

Create the survey collection:创建survey集合:

db.survey.insertMany([
{
_id: 1,
results: [
{ item: "A", score: 5 },
{ item: "B", score: 8 }
]
},
{
_id: 2,
results: [
{ item: "C", score: 8 },
{ item: "B", score: 4 }
]
}
] )

The following operation removes all elements from the results array that contain both a score field equal to 8 and an item field equal to "B":以下操作将从results数组中删除所有同时包含等于8score字段和等于"B"item字段的元素:

db.survey.updateMany(
{ },
{ $pull: { results: { score: 8 , item: "B" } } }
)

The $pull expression applies the condition to each element of the results array as though it were a top-level document.$pull表达式将条件应用于results数组的每个元素,就像它是一个顶级文档一样。

After the operation, the results array contains no documents that contain both a score field equal to 8 and an item field equal to "B".操作后,results数组不包含同时包含等于8score字段和等于"B"item字段的文档。

{ _id: 1, results: [ { item: 'A', score: 5 } ] },
{
_id: 2,
results: [ { item: 'C', score: 8 }, { item: 'B', score: 4 } ]
}

The $pull operator treats each element as a top-level object. The query is applied to each element. The expression does not need to use $elemMatch to specify match conditions.$pull运算符将每个元素视为顶级对象。查询应用于每个元素。表达式不需要使用$elemMatch来指定匹配条件。

On the contrary, the following operation does not $pull any elements from the original collection:相反,以下操作不会从原始集合中提取任何元素:

db.survey.updateMany(
{ },
{ $pull: { results: { $elemMatch: { score: 8 , item: "B" } } } }
)

Note

Drop the survey collection with:使用以下命令删除survey集:

Then recreate it to run this example.然后重新创建它以运行此示例。

Remove Documents from Nested Arrays从嵌套数组中删除文档

Create a new survey collection with documents that are embedded in nested arrays.使用嵌套数组中嵌入的文档创建新的survey集合。

db.survey.drop()

db.survey.insertMany( [
{
_id: 1,
results: [
{
item: "A",
score: 5,
answers: [ { q: 1, a: 4 }, { q: 2, a: 6 } ]
},
{
item: "B",
score: 8,
answers: [ { q: 1, a: 8 }, { q: 2, a: 9 } ]
}
]
},
{
_id: 2,
results: [
{
item: "C",
score: 8,
answers: [ { q: 1, a: 8 }, { q: 2, a: 7 } ]
},
{
item: "B",
score: 4,
answers: [ { q: 1, a: 0 }, { q: 2, a: 8 } ]
}
]
}
] )

Then you can specify multiple conditions on the elements of the answers array with $elemMatch:然后,您可以使用$elemMatchanswers数组的元素上指定多个条件:

db.survey.updateMany(
{ },
{
$pull:
{
results:
{
answers: { $elemMatch: { q: 2, a: { $gte: 8 } } }
}
}
}
)

The operation updated the results array in each document it matched. 该操作更新了它匹配的每个文档中的结果数组。db.collection.updateMany() removed documents from results when an element of the embedded answers array matched the selection conditions in the highlighted line.当嵌入的answers数组的元素与突出显示的行中的选择条件匹配时,db.collection.updateMany()results中删除文档。

{
_id: 1,
results: [
{
item: 'A',
score: 5,
answers: [ { q: 1, a: 4 }, { q: 2, a: 6 } ]
}
]
},
{
_id: 2,
results: [
{
item: 'C',
score: 8,
answers: [ { q: 1, a: 8 }, { q: 2, a: 7 } ]
}
]
}