从MongoDB中的内部数组元素中删除字段

从MongoDB中的内部数组元素中删除字段,mongodb,Mongodb,假设我有: db.test.insert({foos: [{bars: [{}, {}]}]}); db.test.insert({foos: [{bars: [{}, {}]}]}); 现在我想删除所有foo的所有bar字段。我该怎么做 db.test.update({}, {$unset: {"foos.bars": 1}}); 及 什么都不做 db.test.update({}, {$pull: {"foos.$.bars": {}}}); 给出错误: “如果没有包含数组的相应查询字

假设我有:

db.test.insert({foos: [{bars: [{}, {}]}]});
db.test.insert({foos: [{bars: [{}, {}]}]});
现在我想删除所有foo的所有bar字段。我该怎么做

db.test.update({}, {$unset: {"foos.bars": 1}});

什么都不做

db.test.update({}, {$pull: {"foos.$.bars": {}}});
给出错误:

“如果没有包含数组的相应查询字段,则无法应用位置运算符。”


非常感谢您的帮助。

在数组中的子文档上添加一个exist查询似乎可以实现以下目的:

db.test.remove();
db.test.insert({foos: [{bars: [{"baz": 1} ]}]});
db.test.insert({foos: [{bars: [{"baz": 1} ]}]});
db.test.find({'foos.bars': {$exists: true}}).count();
db.test.update({'foos.bars': {$exists: true}}, {$unset: {'foos.$.bars': 1}}, false, true);
db.test.find({'foos.bars': {$exists: true}}).count();
db.test.remove();
db.test.insert({foos: [{bars: [{"baz": 1} ]}]});
db.test.insert({foos: [{bars: [{"baz": 1} ]}]});
db.test.find({'foos.bars': {$exists: true}}).count();
db.test.update({'foos.bars': {$exists: true}}, {$unset: {'foos.$.bars': 1}}, false, true);
db.test.find({'foos.bars': {$exists: true}}).count();