从现有 MongoDB 条目中删除键/值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10146735/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Deleting a key/value from existing MongoDB entry
提问by Chris
I need to delete a certain key and value from every entry in a particular collection. I've looked into remove and that seems to be for only entire entries. Looking at update, I don't believe updating a particular key with null or an empty string would achieve what I'm trying to do. I'm very much a beginner with mongodb, so please excuse my ignorance.
我需要从特定集合中的每个条目中删除某个键和值。我已经研究过删除,这似乎只适用于整个条目。查看更新,我不相信用 null 或空字符串更新特定键会实现我想要做的事情。我是 mongodb 的初学者,所以请原谅我的无知。
Long story short, how can I turn
长话短说,我该如何转身
{
"_id" : 1234,
"name" : "Chris",
"description" : "Awesome"
}
into
进入
{
"_id" : 1234,
"name" : "Chris"
}
without deleting the entry and creating a new one, or using any non-mongodb commands? Thanks!
不删除条目并创建新条目,或使用任何非 mongodb 命令?谢谢!
回答by Bee San
Try $unset
in a call to update()
.
尝试$unset
调用update()
。
Like this:
像这样:
db.collection_name.update({ _id: 1234 }, { $unset : { description : 1} })
And, as vikneshwarcommented, if you want to remove one field from all (or multiple) documents you can use updateMany()
like this:
而且,正如vikneshwar评论的那样,如果您想从所有(或多个)文档中删除一个字段,您可以updateMany()
像这样使用:
db.collection_name.updateMany({}, { $unset : { description : 1} })
回答by aspadacio
To reference a package and remove various "keys", try this
要引用一个包并删除各种“键”,试试这个
db['name1.name2.name3.Properties'].remove([ { "key" : "name_key1" }, { "key" : "name_key2" }, { "key" : "name_key3" } )]
回答by Adrien M.
Also think about upsert()
that will insert your row as a new document if _id
does not exist or update the existing document if any.
还要考虑upsert()
将您的行作为新文档插入(如果_id
不存在)或更新现有文档(如果有)。