我在mongodb中有以下json文件:
{
"_id" : ObjectId("59de156faf75d539b47e8db3"),
"user" : "user1",
"item" : {
"32a1fsd32asfd65asdf65" : {
...
},
"32a1fsd32asfd555" : {
}, ...
}
}
我想执行查询并删除这两个项目中的一个。事实上,我的数据库包含多个用户。因此,为了从mongodb中检索特定的一个,我执行以下操作:
如何检索特定项目并删除其所有字段(例如32a1fsd32asfd65asdf65)?
答案 0 :(得分:1)
根据文档中提供的示例文档,您似乎想要删除子文档item
的属性。
您可以使用$unset更新运算符:
db.getCollection('colName').update(
// find a specific document
{user: 'user1'},
// unset the attribute named "sfd65asdf65"
{$unset: {'item.sfd65asdf65': 1}}
)
鉴于您的问题中提供的文档,上述命令将导致该文档更新为:
{
"_id" : ObjectId("59de156faf75d539b47e8db3"),
"user" : "user1",
"item" : {
"sd32asfd555" : {
...
}
}
}
如果要完全删除item
属性,则运行:
db.getCollection('colName').update(
// find a specific document
{user: 'user1'},
// unset the attribute named "32a1fsd32asfd65asdf65"
{$unset: {'item': 1}}
)
如果要清空item
属性(即删除所有属性但保留item
属性),则运行此命令:
db.getCollection('colName').update(
// find a specific document
{user: 'user1'},
// overwrite the "item" attribute with an empty sub document
{$set: {'item': {}}}
)
您可以找到更多示例in the docs。
答案 1 :(得分:1)
假设我们有一些用户:
> db.test.insert( { _id: 1, user: "bob", field1: 1, field2 :{ field3 : 2 } } )
WriteResult({ "nInserted" : 1 })
> db.test.insert( { _id: 2, user: "fred", field1: 1, field2 :{ field3 : 2 } } )
WriteResult({ "nInserted" : 1 })
然后我们可以使用replaceOne
来查找用户,然后只需替换整个文档,从而删除该文档中的所有字段:
> db.test.replaceOne( { user: "bob"}, { user: "bob" } )
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
然后我们的新文件将如下:
> db.test.find()
{ "_id" : 1, "user" : "bob" }
{ "_id" : 2, "user" : "fred", "field1" : 1, "field2" : { "field3" : 2 } }