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

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

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

当前回答

删除或删除MongoDB中的字段

单次记录 db.getCollection(“用户数据”)。更新({},{$unset: {pi: 1}}) 多重记录 db.getCollection(“用户数据”)。更新({},{$unset: {pi: 1}}, {multi: true})

其他回答

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

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

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版引入的所有位置操作符($[])

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

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

在mongoDB shell中,这段代码可能会有帮助:

db.collection.update({}, {$unset: {fieldname: ""}} )

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

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

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

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