MongoDB 是一个文档型数据库,支持嵌套文档和数组结构。嵌套对象数组是指文档中包含的数组字段,其中每个数组元素又是一个对象(子文档)。
$
定位符更新匹配的数组元素db.collection.update(
{ "arrayField.fieldToMatch": "value" },
{ $set: { "arrayField.$.fieldToUpdate": "newValue" } }
)
示例:
// 更新 comments 数组中 user 为 "John" 的 comment 的 content
db.posts.update(
{ "comments.user": "John" },
{ $set: { "comments.$.content": "Updated comment" } }
)
$[<identifier>]
过滤定位符更新多个匹配元素db.collection.update(
{ /* 查询条件 */ },
{ $set: { "arrayField.$[elem].fieldToUpdate": "newValue" } },
{ arrayFilters: [ { "elem.fieldToMatch": "value" } ] }
)
示例:
// 更新所有 status 为 "pending" 的 items 的 status 为 "completed"
db.orders.update(
{},
{ $set: { "items.$[item].status": "completed" } },
{ arrayFilters: [ { "item.status": "pending" } ] }
)
$push
添加元素到数组db.collection.update(
{ /* 查询条件 */ },
{ $push: { arrayField: newObject } }
)
示例:
// 向 comments 数组添加新评论
db.posts.update(
{ _id: postId },
{ $push: { comments: { user: "Alice", content: "New comment" } } }
)
$pull
移除匹配的数组元素db.collection.update(
{ /* 查询条件 */ },
{ $pull: { arrayField: { field: "value" } } }
)
示例:
// 从 comments 数组中移除 user 为 "Bob" 的所有评论
db.posts.update(
{ _id: postId },
{ $pull: { comments: { user: "Bob" } } }
)
$addToSet
添加唯一元素db.collection.update(
{ /* 查询条件 */ },
{ $addToSet: { arrayField: value } }
)
原因:查询条件没有正确匹配到数组元素,或者使用了错误的定位符。
解决方案:
$
或 $[identifier]
正确定位数组元素arrayFilters
原因:某些更新操作可能导致数组重新排序。
解决方案:
$push
和 $each
组合控制元素位置原因:大型数组的更新操作可能影响性能。
解决方案:
// 假设有以下文档结构
{
_id: "order123",
customer: "John Doe",
items: [
{ productId: "p1", quantity: 2, price: 10, status: "pending" },
{ productId: "p2", quantity: 1, price: 20, status: "shipped" },
{ productId: "p3", quantity: 3, price: 15, status: "pending" }
]
}
// 1. 更新特定商品状态
db.orders.update(
{ _id: "order123", "items.productId": "p1" },
{ $set: { "items.$.status": "shipped" } }
)
// 2. 批量更新所有待处理商品
db.orders.update(
{ _id: "order123" },
{ $set: { "items.$[elem].status": "processed" } },
{ arrayFilters: [ { "elem.status": "pending" } ] }
)
// 3. 添加新商品
db.orders.update(
{ _id: "order123" },
{ $push: { items: { productId: "p4", quantity: 1, price: 30, status: "pending" } } }
)
// 4. 移除特定商品
db.orders.update(
{ _id: "order123" },
{ $pull: { items: { productId: "p3" } } }
)
没有搜到相关的文章