mongodb如何批量修改内嵌文档的属性?
数据结构如上,我需要将内嵌文档里面的isRead属性都设置成true哪要如何来批量的修改它们的值呢?直接看下面的代码:
//连接mongodb
$db = new Manager("mongodb://localhost:27017");
//设置更新语句
$bulk = new BulkWrite();
//注意这一句"['$set' => ["msg.$[].isRead" => true]]",
//我们发现 "msg.$[].isRead" $的后面有一个中括号[],中括号是这里的关键它表示更新所有匹配的属性
$bulk->update(
["username" => "yang", 'msg.isRead' => false],
['$set' => ["msg.$[].isRead" => true]],
['multi' => false, 'upsert' => false]
);
$writeConcern = new WriteConcern(WriteConcern::MAJORITY, 1000);
//执行更新
$result = $db->executeBulkWrite('admin.feedback_msg', $bulk, $writeConcern);
//获取被修改的记录数
echo $result->getModifiedCount();
更多操作如下:
OPERATION
Update all documents in array
db.coll.update({}, {$set: {“a.$[].b”: 2}}) |
Input: {a: [{b: 0}, {b: 1}]} |
Output: {a: [{b: 2}, {b: 2}]} |
Update all matching documents in array
db.coll.update({}, {$set: {“a.$[i].b”: 2}}, {arrayFilters: [{“i.b”: 0}]}) |
Input: {a: [{b: 0}, {b: 1}]} |
Output: {a: [{b: 2}, {b: 1}]} |
Update all matching scalars in array
db.coll.update({}, {$set: {“a.$[i]”: 2}}, {arrayFilters: [{i: 0}]}) |
Input: {a: [0, 1]} |
Output: {a: [2, 1]} |
Update all matching documents in nested array
db.coll.update({}, {$set: {“a.$[i].c.$[j].d”: 2}}, {arrayFilters: [{“i.b”: 0}, {“j.d”: 0}]}) |
Input: {a: [{b: 0, c: [{d: 0}, {d: 1}]}, {b: 1, c: [{d: 0}, {d: 1}]}]} |
Output: {a: [{b: 0, c: [{d: 2}, {d: 1}]}, {b: 1, c: [{d: 0}, {d: 1}]}]} |
Update all scalars in array matching a logical predicate
db.coll.update({}, {$set: {“a.$[i]”: 2}}, {arrayFilters: [{$or: [{i: 0}, {i: 3}]}]}) |
Input: {a: [0, 1, 3]} |
Output: {a: [2, 1, 2]} |
Each array filter must be a predicate over a document with a single field name. Each array filter must be used in the update expression, and each array filter identifier $[<id>] must have a corresponding array filter. <id> must begin with a lowercase letter and not contain any special characters. There must not be two array filters with the same field name.
IMPLEMENTATION DETAILS
The implementation of this feature involved a rewrite of the update system. Users can find all the related tickets here. The design document is attached.