{ 
    name: 'book',
    tags: {
        words: ['abc','123'],
        lat: 33,
        long: 22
    }
}

假设这是一个文档。我如何从这个集合中的所有文档中完全删除“单词”?我希望所有的文件都没有“文字”:

 { 
     name: 'book',
     tags: {
         lat: 33,
         long: 22
     }
}

当前回答

要删除一个字段,您可以使用这个命令(这将应用于集合中的所有文档):

db.getCollection('example').update({}, {$unset: {Words:1}}, {multi: true});

在一个命令中删除多个字段:

db.getCollection('example').update({}, {$unset: {Words:1 ,Sentences:1}}, {multi: true});

其他回答

PyMongo (Python mongo)的解决方案:

db.example.update({}, {'$unset': {'tags.words':1}}, multi=True);

试试这个:如果你的收藏是“榜样”

db.example.update({}, {$unset: {words:1}}, false, true);

参考:

http://www.mongodb.org/display/DOCS/Updating#Updating-%24unset

更新:

上面的链接不再包含“$unset”。如果您想从集合中的所有文档中删除该字段,请确保添加{multi: true};否则,它只会从它找到的第一个匹配的文档中删除它。请参阅更新的文档:

https://docs.mongodb.com/manual/reference/operator/update/unset/

例子:

db.example.update({}, {$unset: {words:1}} , {multi: true});

因为我一直在寻找使用蒙古引擎删除字段的方法时找到这个页面,我猜在这里发布蒙古引擎的方式也可能有帮助:

Example.objects.all().update(unset__tags__words=1)

一开始,我不明白为什么这个问题有赏金(我认为这个问题有一个很好的答案,没有什么可以补充的),但后来我注意到,被接受并被赞了15次的答案实际上是错误的!

是的,你必须使用$unset操作符,但是这个unset操作符将删除集合文档中不存在的words键。所以基本上它什么都不会做。

因此,您需要告诉Mongo在文档标记中查找,然后使用点表示法查找单词。正确的问题是。

db.example.update(
  {},
  { $unset: {'tags.words':1}},
  false, true
)

只是为了完成,我将引用另一种更糟糕的方法,但通过这种方法,您可以使用任何自定义代码更改字段(甚至基于本文档中的另一个字段)。

要删除一个字段,您可以使用这个命令(这将应用于集合中的所有文档):

db.getCollection('example').update({}, {$unset: {Words:1}}, {multi: true});

在一个命令中删除多个字段:

db.getCollection('example').update({}, {$unset: {Words:1 ,Sentences:1}}, {multi: true});