[英]Delete all docs of type ObjectId as _id field in mongodb
In my collection I have few docs with some having _id
field as string and some others as type ObjectId 在我的收藏夹中,我有一些文档,其中一些具有_id
字段作为字符串,而另一些具有_id
类型
{_id:"xxxx"}
{_id:"yyyy"}
{_id:"ObjectId(zzz)"}
{_id:"ObjectId(xxxssssx)"}
I want to delete _id field type ObjectId(here last docs) 我想删除_id字段类型ObjectId(此处为最新文档)
Is there any solution for this? 有什么解决办法吗?
If your document has ObjectId
you can use $type
如果您的文档具有ObjectId
,则可以使用$type
For Example if your collection is like 例如,如果您的收藏是
{
"_id" : "foo"
}
{
"_id" : "bar"
}
{
"_id" : ObjectId("546c52074e418d78ff419897")
}
{
"_id" : ObjectId("546c52074e418d78ff419898")
}
Remove Only ObjectId 仅删除ObjectId
db.coll.remove({_id:{$type:7}})
if your ObjectId is like 如果您的ObjectId像
{_id:"ObjectId(zzz)"}
{_id:"ObjectId(xxxssssx)"}
you can do it 你能行的
db.coll.remove({"_id": {$regex:"^ObjectId"}})
if you want delete only one Document 如果您只想删除一个文档
db.coll.remove({"_id": {$regex:"^ObjectId"}},{justOne:true})
obviously, a specific _id 显然,特定的_id
db.coll.remove({"_id" : "ObjectId(xxxssssx)"})
For deleting object you should write in new ObjectId so below query deleted only given object Id 对于删除对象,您应该输入新的ObjectId,以便在下面的查询中仅删除给定的对象ID
db.collectioName.remove({"_id":new ObjectId("xxxssssx")})
or simply try this 或者只是尝试这个
db.collectioName.remove({"_id": ObjectId("xxxssssx")})
As you cannot update an id How update the _id of one MongoDB Document? 由于您无法更新id,因此如何更新一个MongoDB文档的_id? You should delete your documents and insert them again as code below do this. 您应该删除文档,然后再次插入它们,如下面的代码所示。
db.test.find().forEach(function(item)
{
if(typeof item._id == 'object')
{
var id = item._id.toString().replace('ObjectId(', '').replace(')', '');
db.test.remove({'_id': item._id});
item._id = id;
db.test.insert(item);
}
});
You could make use of the $type
operator. 您可以使用$type
运算符。 The type
of Object Id
is 7
. Object Id
的type
为7
。
db.collection.remove({"_id":{$type:7}})
This removes all the documents having the _id
fields represented as Object Ids
. 这将删除所有_id
字段表示为Object Ids
的文档。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.