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

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

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

当前回答

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

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});

其他回答

我试图做类似的事情,但从嵌入的文档中删除列。我花了一段时间才找到解决办法,这是我看到的第一个帖子,所以我想把它贴在这里,给那些试图做同样事情的人。

假设你的数据是这样的:

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

要从嵌入的文档中删除列词,请执行以下操作:

db.example.update(
  {'tags': {'$exists': true}},
  { $unset: {'tags.$[].words': 1}},
  {multi: true}
)

或者使用updateMany

db.example.updateMany(
  {'tags': {'$exists': true}},
  { $unset: {'tags.$[].words': 1}}
)

$unset只会在值存在时编辑它,但它不会进行安全导航(它不会首先检查标签是否存在),因此在嵌入的文档中需要exists。

这使用了3.6版引入的所有位置操作符($[])

要引用一个包并删除各种“键”, 试试这个

db['name1.name2.name3.Properties'].remove([
{
     "key" : "name_key1"
},
{
     "key" : "name_key2"
},
{
     "key" : "name_key3"
}
)]

PyMongo (Python mongo)的解决方案:

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

默认情况下,update()方法更新单个文档。设置“多参数”以更新符合查询条件的所有文档。

在3.6版更改。 语法:

db.collection.update(
   <query>,
   <update>,
   {
     upsert: <boolean>,
     multi: <boolean>,
     writeConcern: <document>,
     collation: <document>,
     arrayFilters: [ <filterdocument1>, ... ]
   }
)

例子:

db.getCollection('products').update({},{$unset: {translate:1, qordoba_translation_version:1}}, {multi: true})

在你的例子中:

db.getCollection('products').update({},{$unset: {'tags.words' :1}},  {multi: true})

检查“words”是否存在,然后从文档中删除

    db.users.update({"tags.words" :{$exists: true}},
                                           {$unset:{"tags.words":1}},false,true);

True表示匹配时更新多个文档。