我试图一次性为给定团队中的每个玩家增加caps
属性。
每个团队的结构如下:
{
name: "Real Madrid",
players: [ { p_id: "Ronaldo", goal: 135, caps: 134, age: 28 },
{ p_id: "Bale", goal: 75, caps: 45, age: 27 },
{ p_id: "Marcelo", goal: 11, caps: 25, age: 31 },
{ p_id: "Benzema", goal: 125, caps: 95, age: 22 }
]
}
我只能找到有关如何一次更新一个嵌套记录的说明。
db.teams.update({ name: "Real Madrid", "players.p_id" : Ronaldo },
{ $inc : { players.$.caps : 1 });
我可以一次更新所有记录吗?我可以
我会在这里为其他人提供解决方案:
var bulk = db.teams.initializeOrderedBulkOp(),
count = 0;
db.teams.find({ name: "Real Madrid" }).forEach( function(doc) {
var players = doc["players"];
for( var i = 0; i < players.length; i++) {
bulk.find(
{
"_id": doc._id,
"players" : { $elemMatch : { "goal" : players[i]["goal"] }}
}).update({
$inc : { "players.$.goal" : 3 }
});
}
bulk.execute();
});